2013-08-06 32 views
0

我试图用HTMLAgility解析如下:HtmlAgility Xpath的问题

<span class="button"> 
<a role="anotherbutton" href="/gofor/15555445554/be?ref=t">Me</a> 
</span> 

像这样的东西:

foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//span[@class = 'button']/a[@role = 'anotherbutton']")) 
     { 
      string att = link.Attributes["href"].Value; 
      txt_htmlResults.Text += att.ToString() + "\n";  
     } 

不过,我总是得到空例外......我的目的是让15555445554.有人可以帮忙吗?谢谢你在前进

+1

凡在你的foreach循环不空例外发生的? –

+0

你有调试过吗?你有没有证实'link.Attributes [“href”]'实际上会返回一些东西? – Arran

+0

问题是在doc.DocumentNode.SelectNodes它返回空.... Xpath是不正确的如果我把例如// a [@href]我得到页面中的所有hrefs .. – Jim

回答

1

把它扔在一个文本文件我的C盘上:

HtmlDocument doc = new HtmlDocument(); 
    doc.Load("C:\\temp\\stackhtml.html"); 
    //string link = doc.DocumentNode.SelectSingleNode("//span[@class='button']//a").OuterHtml; 
    string rawLink = doc.DocumentNode.SelectSingleNode("//span[@class='button']//a").GetAttributeValue("href", "unkown"); 
    Console.WriteLine("rawLink: " + rawLink); 
    string cleanedLink = rawLink.Substring(rawLink.IndexOf("r/")+2,rawLink.IndexOf("/b")-rawLink.IndexOf("r/")-2); 
    Console.WriteLine("cleanedLink: " + cleanedLink); 
    Console.ReadLine(); 

结果:

enter image description here