2013-03-18 83 views
1

我是新來的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

回答

1

如果您熟悉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 
     } 
} 

注:我沒有運行或測試此代碼