2013-05-04 79 views
0

我試圖解析雅虎財經頁面的股票符號和公司名稱的列表。我使用的網址是:http://uk.finance.yahoo.com/q/cp?s=%5EFTSE從HTMLAgiltyPack解析結果

我使用的代碼是;

HtmlAgilityPack.HtmlDocument page = new HtmlWeb().Load("http://uk.finance.yahoo.com/q/cp?s=%5EFTSE"); 

     var titles = page.DocumentNode.SelectNodes("//td[@class='yfnc_tabledata1']"); 
    // Returns all titles on the home page of this site in an array. 

     foreach (var title in titles) 
     { 
      txtLog.AppendText(title.InnerHtml + System.Environment.NewLine); 

     } 

txtLog.AppendText行只是我測試。代碼正確地獲取每個包含td節點下的yfnc_tabledata1類的行。現在,當我在foreach循環中,我需要解析標題以從以下HTML中獲取符號和公司名稱;

<b><a href="/q?s=GLEN.L">GLEN.L</a></b> 
GLENCORE XSTRAT 
<b>343.95</b> <nobr><small>3 May 16:35</small></nobr> 
<img width="10" height="14" style="margin-right:-2px;" border="0" 
src="http://l.yimg.com/os/mit/media/m/base/images/transparent-1093278.png" 
class="pos_arrow" alt="Up"> <b style="color:#008800;">12.80</b> 
<bstyle="color:#008800;"> (3.87%)</b> 68,086,160 

是否可以解析解析文檔的結果?我有點不確定從哪裏開始。

+0

你試過裝載部分HTML回一個'HtmlDocument'? – 2013-05-04 13:01:09

回答

0

你只需要從你所在的位置繼續進行一些XPATH提取工作。有很多可能性。難度是所有的yfnc_tabledata1節點都處於同一水平。這裏是你如何能做到這一點(在一個控制檯應用程序示例將傾倒的符號和公司的列表):

HtmlAgilityPack.HtmlDocument page = new HtmlWeb().Load("http://uk.finance.yahoo.com/q/cp?s=%5EFTSE"); 

// get directly the symbols under the 1st TD element. Recursively search for an A element that has an HREF attribute under this TD. 
var symbols = page.DocumentNode.SelectNodes("//td[@class='yfnc_tabledata1']//a[@href]"); 

foreach (var symbol in symbols) 
{ 
    // from the current A element, go up two level and get the next TD element. 
    var company = symbol.SelectSingleNode("../../following-sibling::td").InnerText.Trim(); 
    Console.WriteLine(symbol.InnerText + ": " + company); 
} 

更多關於XPath軸位置:XPATH Axes