HTML解析利器-HtmlAgility學習

來源:互聯網
上載者:User

標籤:des   style   class   blog   code   java   

原文:HTML解析利器-HtmlAgility學習

HtmlAgility是一個開源的Html解析庫,據說是C#版的JQuery,功能非常強大。

該篇學習它的解析功能,還可以類比使用者請求,建立html,設定代理等等,暫先不研究。

 

 

----------------------------------------------------------------------------

1.簡單例子

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using HtmlAgilityPack;namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            HtmlWeb webClient = new HtmlWeb();            HtmlDocument doc = webClient.Load("http://www.baidu.com");            var rootNode = doc.DocumentNode;            HtmlNodeCollection categoryNodeList = rootNode.SelectNodes("//html[1]/body[1]");            foreach (var item in categoryNodeList)            {                Console.WriteLine("item: " + item.Name);            }            Console.Read();        }    }}

算是第一個Hellow world,扒的百度頁面。

----------------------------------------------------------------------------

2.讀取

那麼,如果是載入本地的Html或者直接讀流,字串。可以這麼做

HtmlDocument doc = new HtmlDocument();doc.Load(@"D:\xxx.mht", Encoding.UTF8, false);

 

public void LoadHtml(string html);//直接讀字串化的htmlpublic void Load(Stream stream);//流public void Load(string path);//本地路徑

 

HtmlDocumen其本身也提供檢測編碼的方法。

HtmlWeb主要是自動檢測編碼,如果要自訂編碼可以改其中屬性。OverrideEncoding, AutoDetectEncoding。而HtmlDocument對編碼的操作反而不一樣,指定在參數中,估計是自動檢測編碼已經很強大了把,很少要自己指定。。。。

 

----------------------------------------------------------------------------

3.節點選擇

rootNode.SelectNodesrootNode.SelectSingleNode

選擇節點和選擇單個節點。

用SelectNodes為例,看一下參數

rootNode.SelectNodes("//html[1]/body[1]");

"//"雙斜杠表示從根節點尋找所有子節點

"/"單斜杠表示只尋找第一層子節點

"./"點斜杠表示從當前節點開始尋找

 

[]中括弧中的代表相同名字的子節點索引。

var resultList = rootNode.SelectNodes("//html[1]/body[1]/div[1]/div[position()<5]");//取前4個元素resultList = rootNode.SelectNodes("//html[1]/body[1]/div[1]/div[last()]");//取最後1個元素resultList = rootNode.SelectNodes("//html[1]/body[1]/div[1]/div[@id]");//取所有有id屬性的元素resultList = rootNode.SelectNodes("//html[1]/body[1]/div[1]/div[@id=‘head‘]");//取屬性id值為head的元素

更多屬性可以在W3SCHOOL查看http://www.w3school.com.cn/xpath/xpath_functions.asp

 

 取屬性

doc.Attributes["id"];

 取元素

doc.GetElementbyId("id");

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.