2017-09-24 61 views
1

我想解析一個網站。我需要在HTML文件中包含一些特定單詞的鏈接。我知道如何找到「href」屬性,但我不需要所有這些屬性,無論如何要這樣做?例如,我可以在HtmlAgilityPack中使用正則表達式嗎?從C#中的HTML代碼獲取特定單詞的鏈接#

HtmlNode links = document.DocumentNode.SelectSingleNode("//*[@id='navigation']/div/ul"); 

foreach (HtmlNode urls in document.DocumentNode.SelectNodes("//a[@]")) 
{ 
    this.dgvurl.Rows.Add(urls.Attributes["href"].Value); 
} 

我正在試圖尋找HTML代碼中的所有鏈接。

回答

1

如果你有一個HTML文件中像這樣:

<div class="a"> 
    <a href="http://www.website.com/"></a> 
    <a href="http://www.website.com/notfound"></a> 
    <a href="http://www.website.com/theword"></a> 
    <a href="http://www.website.com/sub/theword"></a> 
    <a href="http://www.website.com/theword.html"></a> 
    <a href="http://www.website.com/other"></a> 
</div> 

你正在尋找例如下面的話:thewordother。您可以定義一個正則表達式,然後使用LINQ來獲取鏈接匹配你的正則表達式像這樣的屬性href

Regex regex = new Regex("(theworld|other)", RegexOptions.IgnoreCase); 

HtmlNode node = htmlDoc.DocumentNode.SelectSingleNode("//div[@class='a']"); 
List<HtmlNode> nodeList = node.SelectNodes(".//a").Where(a => regex.IsMatch(a.Attributes["href"].Value)).ToList<HtmlNode>(); 

List<string> urls = new List<string>(); 

foreach (HtmlNode n in nodeList) 
{ 
    urls.Add(n.Attributes["href"].Value); 
} 

注意,有一個contains關鍵字使用XPath,但你必須複製的條件每個字你正在尋找這樣的:

node.SelectNodes(".//a[contains(@href,'theword') or contains(@href,'other')]") 

還有對XPATH一個matches關鍵字,不幸的是它僅適用於XPath 2.0和HtmlAgilityPack使用XPath 1.0。使用XPATH 2.0,你可以這樣做:

node.SelectNodes(".//a[matches(@href,'(theword|other)')]") 
0

我找到了這個,這對我很有用。

HtmlNode links = document.DocumentNode.SelectSingleNode("//*[@id='navigation']/div/ul"); 
    foreach (HtmlNode urls in document.DocumentNode.SelectNodes("//a[@]")) 
     { 
      var temp = catagory.Attributes["href"].Value; 
      if (temp.Contains("some_word")) 
       { 
       dgv.Rows.Add(temp); 
       } 
     } 
+1

「HtmlNode links = ...;'的目的是什麼?該聲明是否應該刪除? – AdrianHHH

相關問題