HtmlAgilityPack 網頁解析器 (爬蟲的應用)

2016/12/21 17:31 Chieh-cheng Tsao HttpWebRequest C#

前言

關於上次某篇講的

HttpWebRequest 取得 網頁資訊

再來就是 網頁  爬蟲的應用

 某次作了 OpenSource 的專案

需要大量的使用 爬蟲的功能來解析網頁

所以研究了許多套件

最終 找的一個方便且好懂的套件

他就是 HtmlAgilityPack 

HtmlAgilityPack 

(1)WebClient

            var client = new WebClient();
            var ms = new MemoryStream(client.DownloadData("http://jtsb.mlit.go.jp/jtsb/railway/rail-accident-toukei.php"));
            var HtmlPage = new HtmlAgilityPack.HtmlDocument();
            //因為抓取網頁為日文,所以要先轉換成日文編碼
            HtmlPage.Load(ms, Encoding.GetEncoding(65001));
            //取得想要的DOM
            var result = HtmlPage.DocumentNode.SelectNodes("//table[@class='toukei']/tr");

                for (int i = 2; i < result.Count - 1; i++)
                {

                    // 取得 tr 內的 DOM
                    HtmlDocument hdc = new HtmlDocument();
                    hdc.LoadHtml(result[i].InnerHtml);
                    var childes = hdc.DocumentNode.SelectNodes("td|th");
                 }

(2)HttpWebResponse

            // 取得回應
            HttpWebResponse response = null;
            var request = (HttpWebRequest)HttpWebRequest.Create(Url);
            //依照需求不同而改變Method
            request.Method = "GET";
            //假裝是使用者封包
            request.UserAgent = "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.2;.NET CLR 1.1.4322)";

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                // StatusCode 非 200 從 WebException 抓 Response
                response = (HttpWebResponse)e.Response;
            }

            StreamReader sr = new StreamReader(response.GetResponseStream(),
            //設定編碼
            System.Text.Encoding.GetEncoding(response.CharacterSet));
            var HtmlContent = sr.ReadToEnd();
            response.Close();
            sr.Close();

            //建置解析網頁物件
            var HtmlPage = new HtmlAgilityPack.HtmlDocument();
            HtmlPage.LoadHtml(Content);
            var result = HtmlPage.DocumentNode.SelectNodes("//textarea[@id='clipboard-text']");
            ....(再來就是跟上面一樣)....

以上 就是 我使用的網頁解析器

發表評論

此篇評論

暫無討論