Html Agility Pack解析Html(C#爬虫利器)

有个需求要写网络爬虫,以前接触过一个叫Html Agility Pack这个解析html的库,这次又要用到,然而发现以前咋用的已经不记得了,现在从头开始记录一下使用过程.

Html Agility Pack官网.大家用的同时也可以去github上star一下这个项目,支持一下.net开源项目.(首页上有其github的项目地址)

加载Html

有几种方式可以加载Html

  1. 从流(Stream)中加载

    HtmlWebRequest req = WebRequest.Create("https://www.cnblogs.com/Laggage/p/10740012.html") as HtmlWebRequest;
    HtmlWebResponse res = req.GetResponse() as HtmlWebResponse;
    Stream s = res.GetResponseStream();
    

    HtmlDocument doc = new HtmlDocument();
    doc.Load(s)

  2. 从字符串加载Html(直接用的官网的一个例子)

    var html = @"<!DOCTYPE html>
    <html>
    <body>
        <h1>This is <b>bold</b> heading</h1>
        <p>This is <u>underlined</u> paragraph</p>
        <h2>This is <i>italic</i> heading</h2>
    </body>
    </html> ";
    

    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(html);

    var htmlBody = htmlDoc.DocumentNode.SelectSingleNode("//body");

    Console.WriteLine(htmlBody.OuterHtml);

  3. 从文件加载

    string path = @"test.html";
    

    HtmlDocument doc = new HtmlDocument();
    doc.Load(path);

    HtmlNode node = doc.DocumentNode.SelectSingleNode("//body");

    Console.WriteLine(node.OuterHtml);

  4. 还可以直接从网络上加载(套用官网的例子)

    string html = @"http://html-agility-pack.net/";
    

    HtmlWeb web = new HtmlWeb();

    HtmlDocument htmlDoc = web.Load(html);

    HtmlNode node = htmlDoc.DocumentNode.SelectSingleNode("//head/title");

    Console.WriteLine("Node Name: " + node.Name + "\n" + node.OuterHtml);

解析html

利用Html Agility Pack解析起html还是很容易的.主要利用XPath语法.同样套用官网的代码.

HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);

string name = htmlDoc.DocumentNode
.SelectNodes("//td/input") //双斜杠表示查询所有的子节点,如果是只要查询范围在当前节点的下一层子节点,则只用一个子节点.
.First()
.Attributes["value"].Value;

主要就是利用 HtmlNode.SelectSingleNode()和HtmlNode.SelectNodes()方法来寻找节点.



这是 Html Agility Pack 官网首页的一段html,现在以要拿到其中的pre标签的所有内容为例.

string url = @"https://html-agility-pack.net/";
HtmlWeb web = new HtmlWeb();

HtmlDocument doc = web.Load(html);

string text = doc.DocumentNode
.SelectSingleNode("//div[@class='side-body container-none page-index']/div[@class='container-examples-index d-flex justify-content-center']/pre")
.InnerText;

Console.WriteLine(text);

具体的XPath语法可以看W3C的教程:W3CXPath教程.

  </div>
posted @ 2019-04-20 10:41  Laggage  阅读(1005)  评论(0编辑  收藏  举报