淺談C#解析網頁

來源:互聯網
上載者:User

標籤:path   知識   開始   string   des   log   pat   default   build   

最近做了一個項目,要求擷取各大主流網頁上的關鍵資訊,本人以前瞭解過網頁爬蟲的知識,所以想到了網頁爬蟲了實現功能

第一次嘗試:

採用webclient擷取遠程網頁的內容,然後採用Regex進行過濾

但,由於Regex對我來說,書寫起來比較複雜,研究個大半個月,一點進展都沒有,每天看著Regex像看天書(回頭需要向正則牛逼的人請教一下)

第一次嘗試失敗,項目馬上就要驗收了,這個功能一直卡殼了,,,,,,,,

 

突然有一次,在網上看到了有人提及到了HtmlAgilityPack這個開源的工具包,本想著試一下的態度(因為我對這個網頁解析已經不抱有希望了)

僅僅有了幾行的代碼,居然跟我的需求一樣實現了,萬分高興(此處使用HtmlAgilityPack需要學習一下xpath的一點知識,不過那些都很簡單,比起正則太easy了)

好了,廢話不多說,上代碼

 

1、去官網上下載一個HtmlAgilityPack包,地址:http://htmlagilitypack.codeplex.com/

2、根據自己項目的.net版本,選擇適合的版本,引入項目

3、開始寫代碼了

HtmlAgilityPack基本跟所有的類一樣,直接使用裡面的方法和屬性就行,具體可以參考官網

//擷取網頁指定內容        public void GetHtml()        {            string htmlpath = "http://kaijiang.aicai.com/fcssq/";            //建立對象            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();            WebClient webclient = new WebClient();            webclient.Credentials = CredentialCache.DefaultCredentials;//網路憑證            Byte[] pageData = webclient.DownloadData(htmlpath);           // string pagehtml = Encoding.Default.GetString(pageData); //預設編碼            string pagehtml = Encoding.UTF8.GetString(pageData);//UTF-8編碼            //用htmlagilitypack 解析網頁內容            //載入html            doc.LoadHtml(pagehtml);            //通過xpath 選中指定元素;xpath 參考:http://www.w3school.com.cn/xpath/xpath_syntax.asp            HtmlAgilityPack.HtmlNode htmlnode = doc.DocumentNode.SelectSingleNode("//div[@id=‘jq_openResult‘]");            StringBuilder sb = new StringBuilder();            string s = "";                        HtmlAgilityPack.HtmlNodeCollection nodecollection = htmlnode.ChildNodes;            for (int i = 0; i < nodecollection.Count; i++)            {                if (nodecollection[i].InnerText.Trim()!="")                {                    TextBox1.Text += nodecollection[i].InnerText + "-";                                    }              }            TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1);            Console.WriteLine(s);        }

至此,HtmlAgilityPack就完全按照自己的要求解析出來了網頁上的任何你想要的,是不是很神奇~~

淺談C#解析網頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.