废话不多说, 直接说需求。
公司的网站需要抓取其他网站的文章,但任务没到我这,同事搞了一下午没搞出来。由于刚刚到公司, 想证明下自己,就把活揽过来了。因为以前做过,觉得应该很简单,但当我开始做的时候,我崩溃了,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));
}
运行结果如图:
打完收工。
使用HttpWebRequest和HtmlAgilityPack抓取网页(拒绝乱码,拒绝正则表达式),布布扣,bubuko.com