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

有個需求要寫網絡爬蟲,之前接觸過一個叫Html Agility Pack這個解析html的庫,此次又要用到,然而發現之前咋用的已經不記得了,如今從頭開始記錄一下使用過程.html

Html Agility Pack官網.你們用的同時也能夠去github上star一下這個項目,支持一下.net開源項目.(首頁上有其github的項目地址)node

加載Html

有幾種方式能夠加載Htmlgit

  1. 從流(Stream)中加載github

    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(直接用的官網的一個例子)web

    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. 從文件加載markdown

    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語法.一樣套用官網的代碼.ide

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標籤的全部內容爲例.flex

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教程.url

相關文章
相關標籤/搜索