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";

 

一句话,非常好用!

posted @ 2012-01-05 18:32  KymoWang  阅读(11389)  评论(5编辑  收藏  举报