Html Agility Pack是用C#写的开源Html Parser。
在抓取163首页(http://www.163.com)代码如下:
HtmlWeb hw = new HtmlWeb();
string url = @"http://www.163.com";
HtmlDocument doc = hw.Load(url);
doc.Save("mshome.htm");
不过有点问题是抓取的Code乱码了。
通过跟踪代码发现通过修改HtmlWeb.cs 中的第1466行(1.4.0.0版) 文件可以解决这个问题。
方法名为:
private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc, IWebProxy proxy, ICredentials creds)
原始实现源代码:
...
...
Encoding respenc = !string.IsNullOrEmpty(resp.ContentEncoding)
? Encoding.GetEncoding(resp.ContentEncoding)
: null;
...
...
修改后的代码:
//Encoding respenc = !string.IsNullOrEmpty(resp.ContentEncoding)
// ? Encoding.GetEncoding(resp.ContentEncoding)
// : null;
//update By Glen begin
Encoding respenc;
if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length > 0))
{
respenc = System.Text.Encoding.GetEncoding(resp.ContentEncoding);
}
else if ((resp.CharacterSet != null) && (resp.CharacterSet.Length > 0))//根据Content-Type中获取的charset
{
if (string.Compare(resp.CharacterSet, "ISO-8859-1", true, System.Globalization.CultureInfo.InvariantCulture) == 0)
respenc = System.Text.Encoding.GetEncoding("GB2312");
else
respenc = System.Text.Encoding.GetEncoding(resp.CharacterSet);
}
else
{
respenc = System.Text.Encoding.GetEncoding("GB2312");
}
//update By Glen end
重新编译一下,就不会中文乱码了...