C#解析html文檔


當我們需要解析一個web頁面的時候,如果非常簡單,可以用字符串查找的方式,復雜一點可以用正則表達式,但是有時候正則很麻煩的,因為html代碼本身就比較麻煩,像常用的img標簽,這個東東到了瀏覽器上就沒了閉合標簽(一直還沒搞懂為什么),想用XML解析,也是同樣的原因根本解析不了,今天發現一個解析html控件,用了一下,非常好用。

這個控件叫做Html Agility Pack,主頁在這兒:http://htmlagilitypack.codeplex.com/

這兒還有一篇blog介紹怎么使用的 (English):http://olussier.net/2010/03/30/easily-parse-html-documents-in-csharp/

我直接把例子貼這兒,一看就明白。因為是作為xml解析的,所以呢,少不了XPath,如果不懂這個東西的話,趕緊看看吧,現在xpath語法都擴展到css里面了,語法比較簡單,先看看基礎的就行了。

最基本的使用方法不是SelectSingleNode,而是GetElementById,這是與XmlDocument不同的地方。

// The HtmlWeb class is a utility class to get the HTML over HTTP
HtmlWeb htmlWeb = new HtmlWeb();
 
// Creates an HtmlDocument object from an URL
HtmlAgilityPack.HtmlDocument document = htmlWeb.Load("http://www.somewebsite.com");
 
// Targets a specific node
HtmlNode someNode = document.GetElementbyId("mynode");
 
// If there is no node with that Id, someNode will be null
if (someNode != null)
{
  // Extracts all links within that node
  IEnumerable
 
 
 
         
          
  
  
   allLinks = someNode.Descendants("a");
 
  // Outputs the href for external links
  foreach (HtmlNode link in allLinks)
  {
    // Checks whether the link contains an HREF attribute
    if (link.Attributes.Contains("href"))
    {
      // Simple check: if the href begins with "http://", prints it out
      if (link.Attributes["href"].Value.StartsWith("http://"))
        Console.WriteLine(link.Attributes["href"].Value);
    }
  }
}
 
 
 
         

使用xpath

// Extracts all links under a specific node that have an href that begins with "http://"
HtmlNodeCollection allLinks = document.DocumentNode.SelectNodes("//*[@id='mynode']//a[starts-with(@href,'http://')]");
 
// Outputs the href for external links
foreach (HtmlNode link in allLinks)
    Console.WriteLine(link.Attributes["href"].Value);

One more

xpath = "//table[@id='1' or @id='2' or @id='3']//a[@onmousedown]"; 
xpath = "//ul[@id='wg0']//li[position()<4]/h3/a"; 
xpath = "//div[@class='resitem' and position()<4]/a";
xpath = "//li[@class='result' and position()<4]/a";

 

一句話,非常好用!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM