我的數(shù)據(jù)通過一個(gè)TextBox輸入,這些代碼是寫在一個(gè)button的點(diǎn)擊事件里的。
網(wǎng)頁數(shù)據(jù)抓取大概分為兩步,第一步是獲取網(wǎng)頁源代碼:
具體注釋如下:
var currentUrl = TextBox1.Text;//獲得要抓取的網(wǎng)頁的URL地址 var request = WebRequest.Create(currentUrl) as HttpWebRequest;//請(qǐng)求對(duì)象 var response=request.GetResponse()as HttpWebResponse;//定義頁面回應(yīng)對(duì)象
var encode = string.Empty; encode = response.CharacterSet;//獲得網(wǎng)頁的編碼
Stream stream;//數(shù)據(jù)流 if (response.ContentEncoding.ToLower() == "gzPRessionMode.Decompress); } else { stream = response.GetResponseStream(); }//解壓縮 var sr = new StreamReader(stream,Encoding.GetEncoding(encode));//定義數(shù)據(jù)流讀取對(duì)象 var html = sr.ReadToEnd(); sr.Close(); HtmlDocument document=new HtmlDocument(); document.LoaDHTML(html);//將數(shù)據(jù)存入document
得到了網(wǎng)頁源代碼,接下來就是對(duì)其解析,就是第二步:
解析可以使用正則表達(dá)式或是Spilt等字符串操作方法。
根據(jù)源代碼寫出的Xpath,利用節(jié)點(diǎn)得到位于兩個(gè)節(jié)點(diǎn)之間的數(shù)據(jù):
我的對(duì)象網(wǎng)頁就是我的博客主頁http://home.VEVb.com/u/xuwanghu/
string sumLine = document.DocumentNode.SelectSingleNode("http://body//ul[@id='user_profile']").InnerText;
string yuanlin = sumLine2.ToString().Split(':')[0].Split('博')[0];
這樣子,就將園齡存入了yuanlin,也就實(shí)現(xiàn)了抓取網(wǎng)頁數(shù)據(jù)的功能。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注