C#抓取网页乱码

pjw100 pjw100 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我抓取的地址是搜狐焦点论坛的,例如这个地址:
http://sz.focus.cn/msglist/51806/

编码我试过很多种,gb2312,utf-8...都试过了,始终是乱码。
抓取html代码的程序很简单

能否有哪位大神写个简单的抓取,就应对上面那个地址,乱码整的心慌慌啊。


public static void GetWebContent(string url)
{
try
{

HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
//myHttpWebRequest.SendChunked = true;
//myHttpWebRequest.TransferEncoding = "gb2312";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
myHttpWebRequest.ContentType = "text/html";
//Console.WriteLine("The encoding method used is: " + myHttpWebResponse.ContentEncoding);
Console.WriteLine("字符编码:" + myHttpWebResponse.CharacterSet);
Stream webStream = myHttpWebResponse.GetResponseStream();
string encoding = myHttpWebResponse.CharacterSet;
//经过大量测试发现.NET会将gb2312的编码格式识别为ISO-8859-1,故作此处理
encoding = (encoding == "ISO-8859-1") ? "gb2312" : encoding;
//获取的内容是否属于文本
char seperator = '/';
String contenttype = myHttpWebResponse.ContentType;
// 返回 'text' 如果文本类型是'text/html.
String maintype = contenttype.Substring(0, contenttype.IndexOf(seperator));
// 只保存内容为'text'类型的网页,不保存示图片等其他文件
if (String.Compare(maintype, "text") == 0)
{
Console.WriteLine("\n Content type is 'text'.");
StreamReader sw = new StreamReader(webStream, System.Text.Encoding.GetEncoding(encoding));
Console.WriteLine("网页内容:");
StringBuilder sb = new StringBuilder();
while (sw.Peek() >= 0)
{
string strWebContent = sw.ReadLine();
sb.Append(strWebContent);
}
sw.Close();
sw.Dispose();
webStream.Close();

Console.WriteLine(sb.ToString());
}
else
{
Console.Write("网页内容不是文本无法显示!");
}
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex.Message);
}

}


...全文

相关推荐

评论 3
收藏 已收藏
分享
返回顶部
pjw100
.NET社区 62,274 成员 668,968 内容