廢話不多說, 直接說需求。
公司的網站需要抓取其他網站的文章,但任務沒到我這,同事搞了一下午沒搞出來。由於剛剛到公司, 想證明下自己,就把活攬過來了。因為以前做過,覺得應該很簡單,但當我開始做的時候,我崩潰了,http請求后,得到的是字符串竟然是亂碼,然后就各種百度(谷歌一直崩潰中),最后找到了原因。由於我要抓取的網頁做了壓縮,所以當我抓的時候,抓過來的是壓縮后的,所以必須解壓一下,如果不解壓,不管用什么編碼方式,結果還是亂碼。直接上代碼:

1 public Encoding GetEncoding(string CharacterSet) 2 { 3 switch (CharacterSet) 4 { 5 case "gb2312": return Encoding.GetEncoding("gb2312"); 6 case "utf-8": return Encoding.UTF8; 7 default: return Encoding.Default; 8 } 9 }
public string HttpGet(string url) { string responsestr = ""; HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; req.Accept = "*/*"; req.Method = "GET"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"; using (HttpWebResponse response = req.GetResponse() as HttpWebResponse) { Stream stream; if (response.ContentEncoding.ToLower().Contains("gzip")) { stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress); } else if (response.ContentEncoding.ToLower().Contains("deflate")) { stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress); } else { stream = response.GetResponseStream(); } using (StreamReader reader = new StreamReader(stream, GetEncoding(response.CharacterSet))) { responsestr = reader.ReadToEnd(); stream.Dispose(); } } return responsestr; }
調用HttpGet就可以獲取網址的源碼了,得到源碼后, 現在用一個利器HtmlAgility來解析html了,不會正則不要緊,此乃神器啊。老板再也不用擔心我的正則表達式了。
至於這個神器的用法,園子文章很多,寫的也都挺詳細的,在此不贅余了。
下面是抓取園子首頁的文章列表:
string html = HttpGet("http://www.cnblogs.com/"); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); //獲取文章列表 var artlist = doc.DocumentNode.SelectNodes("//div[@class='post_item']"); foreach (var item in artlist) { HtmlDocument adoc = new HtmlDocument(); adoc.LoadHtml(item.InnerHtml); var html_a = adoc.DocumentNode.SelectSingleNode("//a[@class='titlelnk']"); Response.Write(string.Format("標題為:{0},鏈接為:{1}<br>",html_a.InnerText,html_a.Attributes["href"].Value)); }
運行結果如圖:
打完收工。
由於時間倉促,加上本人文筆不行,如有疑問,歡迎吐槽,吐吐更健康。