htmlagilitypack解析链接和内部文本

问题描述:

我是新来的htmlagilitypack,我试着想出一个办法,我将能够得到从成立这样htmlagilitypack解析链接和内部文本

<div class="std"><div style="border-right: 1px solid #CCCCCC; float: left; height: 590px; width: 190px;"><div style="background-color: #eae3db; padding: 8px 0 8px 20px; font-weight: bold; font-size: 13px;">test</div> 
    <div> 
    <div style="font-weight: bold; margin: 5px 0 -6px;">FEATURED</div> 
    <span class="widget widget-category-link"><a href="http://www.href1.com"><span>cat1</span></a></span> 
    <span class="widget widget-category-link"><a href="http://www.href1.com"><span>cat2</span></a></span> 
</div></div> 

我还没有写一个HTML链接任何代码在C#中,但我想知道是否任何人都可以建议什么标签应指向获取链接和内部文本时,没有HTML ID'。谢谢

+1

“我还没有在C#写任何代码,但”先写一些代码,然后提问。 – 2013-03-18 14:41:52

+1

如果您不喜欢/了解XPath,请考虑使用[CsQuery](https://github.com/jamietre/CsQuery)而不是HTML Agilitiy Pack。它是C#的一个jQuery端口。 – Oded 2013-03-18 14:42:05

如果您熟悉XPATH,您将能够浏览html的元素和属性以获得您想要的任何内容。为了让每一个HREF在你上面如下可以写代码:

const string xpath = "/div//span/a"; 

//WebPage below is a string that contains the text of your example 
HtmlNode html = HtmlNode.CreateNode(WebPage); 
//The following gives you a node collection of your two <a> elements 
HtmlNodeCollection items = html.SelectNodes(xpath); 
foreach (HtmlNode a in items) 
{  
     if (a.Attributes.Contains("href")) 
     //Get your value here 
     { 
      yourValue = a.Attributes["href"].Value 
     } 
} 

注:我没有运行或测试此代码