那位对C#熟悉,指点下为什么我抓取得网页都乱码?
看到网上的一些介绍,但是都不好使StreamReader sr = new StreamReader(myStream, Encoding.GetEncoding("gb2312"));后来想根据网页的字符集改变相应的字符集,方法如下:
StreamReader sr = new StreamReader(myStream,Encoding.GetEncoding(HttpWResp.CharacterSet));还是不行,不知道怎么改,那位指点指点,谢谢!
看到网上的一些介绍,但是都不好使StreamReader sr = new StreamReader(myStream, Encoding.GetEncoding("gb2312"));后来想根据网页的字符集改变相应的字符集,方法如下:
StreamReader sr = new StreamReader(myStream,Encoding.GetEncoding(HttpWResp.CharacterSet));还是不行,不知道怎么改,那位指点指点,谢谢!
你确定目标网页是gb2312编码?你得用与目标网页相对应的编码才行的。有些可能会涉及语言问题,以前我做的抓取日语页面的程序,utf-8格式,在windows下是乱码,在linux是正常的,可能是系统问题。
using System.Net;
using System.Text;
using System.Text.RegularExpressions;class Program
{
// 获取网页的HTML内容,根据网页的charset自动判断Encoding
static string GetHtml(string url)
{
return GetHtml(url, null);
} // 获取网页的HTML内容,指定Encoding
static string GetHtml(string url, Encoding encoding)
{
byte[] buf = new WebClient().DownloadData(url);
if (encoding != null) return encoding.GetString(buf);
string html = Encoding.UTF8.GetString(buf);
encoding = GetEncoding(html);
if (encoding == null || encoding == Encoding.UTF8) return html;
return encoding.GetString(buf);
} // 根据网页的HTML内容提取网页的Encoding
static Encoding GetEncoding(string html)
{
string pattern = @"(?i)\bcharset=(?<charset>[-a-zA-Z_0-9]+)";
string charset = Regex.Match(html, pattern).Groups["charset"].Value;
try { return Encoding.GetEncoding(charset); }
catch (ArgumentException) { return null; }
} // 根据网页的HTML内容提取网页的Title
static string GetTitle(string html)
{
string pattern = @"(?si)<title(?:\s+(?:""[^""]*""|'[^']*'|[^""'>])*)?>(?<title>.*?)</title>";
return Regex.Match(html, pattern).Groups["title"].Value.Trim();
} // 打印网页的Encoding和Title
static void PrintEncodingAndTitle(string url)
{
string html = GetHtml(url);
Console.WriteLine("[{0}] [{1}]", GetEncoding(html), GetTitle(html));
} // 程序入口
static void Main()
{
PrintEncodingAndTitle("http://www.msdn.net/");
PrintEncodingAndTitle("http://www.cnblogs.com/");
PrintEncodingAndTitle("http://www.cnblogs.com/skyiv/");
PrintEncodingAndTitle("http://www.csdn.net/");
PrintEncodingAndTitle("http://news.163.com/");
}
}
/* 程序输出:
[] [MSDN: Microsoft Developer Network]
[System.Text.UTF8Encoding] [博客园 - 程序员的网上家园]
[System.Text.UTF8Encoding] [空间/IV - 博客园]
[System.Text.UTF8Encoding] [CSDN.NET - 中国最大的IT技术社区,为IT专业技术人员提供最全面的信息传播和服务平台]
[System.Text.DBCSCodePageEncoding] [新闻中心_网易新闻]
*/
代码如下:
//获取http页面函数
public string Get_Http(string a_strUrl, int timeout)
{
string strResult;
try
{
HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
myReq.Timeout = timeout;
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.GetEncoding("gb2312"));
//StreamReader sr = new StreamReader(myStream, Encoding.Default);
//StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine() + "");
}
strResult = strBuilder.ToString();
}
catch (Exception exp)
{
strResult = "错误:" + exp.Message;
}
return strResult;
}
Encoding.Default 时抓英文的没事,汉字的上面的几个方法都不行!
Imports System.Net
Imports System.IO
Imports System.TextPublic Class Form1
Public Function Get_Http(ByVal a_strUrl As String, ByVal timeout As Integer) As String Dim strResult As String
Try
Dim myReq As HttpWebRequest = HttpWebRequest.Create(a_strUrl)
myReq.Timeout = timeout
Dim HttpWResp As HttpWebResponse = myReq.GetResponse()
Dim myStream As Stream = HttpWResp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(myStream, Encoding.Default)
'//StreamReader sr = new StreamReader(myStream, Encoding.Default);
'//StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
Dim strBuilder As StringBuilder = New StringBuilder()
While Not sr.EndOfStream strBuilder.Append(sr.ReadLine() + "") End While
sr.Close()
strResult = strBuilder.ToString() Catch exp As Exception strResult = "错误:" + exp.Message
End Try
Return strResult End Function Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As String = Get_Http("http://www.baidu.com", 1000)
End Sub
End Class
结果是这样的
<html><head><meta http-equiv=Content-Type content="text/html;charset=gb2312"><title>百度一下,你就知道 </title><style>body{margin:4px 0}p{margin:0;padding:0}img{border:0}td,p,#u{font-size:12px}#b,#u,#l td,a{font-family:arial}#kw{font:16px Verdana;height:1.78em;padding-top:2px}#b{height:30px;padding-top:4px}#b,#b a{color:#77c}#u{padding-right:10px;line-height:19px;text-align:right;margin:0 0 3px !important;margin:0 0 10px}#sb{height:2em;width:5.6em}#km{height:50px}#l{margin:0 0 5px 15px}#l td{padding-left:107px}p,table{width:650px;border:0}#l td,#sb,#km{font-size:14px}#l a,#l b{margin-right:1.14em}a{color:#00c}a:active{color:#f60}#hp{position:absolute;margin-left:6px}#lg{margin:-26px 0 -44px}#lk{width:auto;line-height:18px;vertical-align:top}form{position:relative;z-index:9}</style></head><body><div id=u><a href=http://passport.baidu.com/?login&tpl=mn>登录</a></div><center><img src=http://www.baidu.com/img/baidu_logo.gif width=270 height=129 usemap="#mp" id=lg><br><br><br><br><table cellpadding=0 cellspacing=0 id=l><tr><td><div id=m><a onclick=s(this) href=http://news.baidu.com>新 闻</a><b>网 页</b><a onclick=s(this) href=http://tieba.baidu.com>贴 吧</a><a onclick=s(this) href=http://zhidao.baidu.com>知 道</a><a onclick=s(this) href=http://mp3.baidu.com>MP3</a><a onclick=s(this) href=http://image.baidu.com>图 片</a><a onclick=s(this) href=http://video.baidu.com>视 频</a></div></td></tr></table><table cellpadding=0 cellspacing=0 style="margin-left:15px"><tr valign=top><td style="height:62px;padding-left:92px" nowrap><form name=f action=s><input type=text name=wd id=kw size=42 maxlength=100> <input type=submit value=百度一下 id=sb><span id=hp><a href=/gaoji/preferences.html>设置</a><br><a href=/gaoji/advanced.html>高级</a></span></form></td></tr></table><p id=km><a href=http://hi.baidu.com>空间</a> <a href=http://www.hao123.com>hao123</a> | <a href=/more/>更多<span style="font-family:宋体">>></span></a></p><p style=height:60px><table cellpadding=0 cellspacing=0 id=lk><tr><td><a href="http://123.baidu.com" target="_blank">百度“老年搜索”上线了!</a></td></tr></table></p><p style=height:30px><a onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.baidu.com')" href=http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com>把百度设为主页</a></p><p style=height:14px><a href=http://e.baidu.com>加入百度推广</a> | <a href=http://top.baidu.com>搜索风云榜</a> | <a href=/home.html>关于百度</a> | <a href=http://ir.baidu.com>About Baidu</a></p><p id=b>©2009 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://www.miibeian.gov.cn target=_blank>京ICP证030173号</a> <img src=http://gimg.baidu.com/img/gs.gif></p><map name=mp><area shape=rect coords="43,22,227,91" href=http://hi.baidu.com/baidu/ target=_blank title="点此进入 百度空间"></map></center></body><script>var w=document.f.wd;function s(o){if(w.value.length>0){var h=o.href;var q=encodeURIComponent(w.value);if(h.indexOf("q=")!=-1){o.href=h.replace(new RegExp("q=[^&$]*"),"q="+q)}else{o.href+="?q="+q}}};(function(){if(new RegExp("q=([^&]+)").test(location.search)){w.value=decodeURIComponent(RegExp.$1)}})();if(navigator.cookieEnabled && !/sug?=0/.test(document.cookie)){document.write('<script src=http://www.baidu.com/js/bdsug.js?v=1.1.0.1><\/script>')};window.onunload=function(){};</script><script>w.focus()</script></html><!--3f96fc2c3e866000-->
Imports System.Net
Imports System.IO
Imports System.TextPublic Class Form1
Public Function Get_Http(ByVal a_strUrl As String, ByVal timeout As Integer) As String Dim strResult As String
Try
Dim myReq As HttpWebRequest = HttpWebRequest.Create(a_strUrl)
myReq.Timeout = timeout
Dim HttpWResp As HttpWebResponse = myReq.GetResponse()
Dim myStream As Stream = HttpWResp.GetResponseStream()
Dim sr As StreamReader = New StreamReader(myStream, Encoding.Default)
'//StreamReader sr = new StreamReader(myStream, Encoding.Default);
'//StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
Dim strBuilder As StringBuilder = New StringBuilder()
While Not sr.EndOfStream strBuilder.Append(sr.ReadLine() + "") End While
sr.Close()
strResult = strBuilder.ToString() Catch exp As Exception strResult = "错误:" + exp.Message
End Try
Return strResult End Function Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim s As String = Get_Http("http://www.baidu.com", 1000)
End Sub
End Class
结果是这样的
<html><head><meta http-equiv=Content-Type content="text/html;charset=gb2312"><title>百度一下,你就知道 </title><style>body{margin:4px 0}p{margin:0;padding:0}img{border:0}td,p,#u{font-size:12px}#b,#u,#l td,a{font-family:arial}#kw{font:16px Verdana;height:1.78em;padding-top:2px}#b{height:30px;padding-top:4px}#b,#b a{color:#77c}#u{padding-right:10px;line-height:19px;text-align:right;margin:0 0 3px !important;margin:0 0 10px}#sb{height:2em;width:5.6em}#km{height:50px}#l{margin:0 0 5px 15px}#l td{padding-left:107px}p,table{width:650px;border:0}#l td,#sb,#km{font-size:14px}#l a,#l b{margin-right:1.14em}a{color:#00c}a:active{color:#f60}#hp{position:absolute;margin-left:6px}#lg{margin:-26px 0 -44px}#lk{width:auto;line-height:18px;vertical-align:top}form{position:relative;z-index:9}</style></head><body><div id=u><a href=http://passport.baidu.com/?login&tpl=mn>登录</a></div><center><img src=http://www.baidu.com/img/baidu_logo.gif width=270 height=129 usemap="#mp" id=lg><br><br><br><br><table cellpadding=0 cellspacing=0 id=l><tr><td><div id=m><a onclick=s(this) href=http://news.baidu.com>新 闻</a><b>网 页</b><a onclick=s(this) href=http://tieba.baidu.com>贴 吧</a><a onclick=s(this) href=http://zhidao.baidu.com>知 道</a><a onclick=s(this) href=http://mp3.baidu.com>MP3</a><a onclick=s(this) href=http://image.baidu.com>图 片</a><a onclick=s(this) href=http://video.baidu.com>视 频</a></div></td></tr></table><table cellpadding=0 cellspacing=0 style="margin-left:15px"><tr valign=top><td style="height:62px;padding-left:92px" nowrap><form name=f action=s><input type=text name=wd id=kw size=42 maxlength=100> <input type=submit value=百度一下 id=sb><span id=hp><a href=/gaoji/preferences.html>设置</a><br><a href=/gaoji/advanced.html>高级</a></span></form></td></tr></table><p id=km><a href=http://hi.baidu.com>空间</a> <a href=http://www.hao123.com>hao123</a> | <a href=/more/>更多<span style="font-family:宋体">>></span></a></p><p style=height:60px><table cellpadding=0 cellspacing=0 id=lk><tr><td><a href="http://123.baidu.com" target="_blank">百度“老年搜索”上线了!</a></td></tr></table></p><p style=height:30px><a onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.baidu.com')" href=http://utility.baidu.com/traf/click.php?id=215&url=http://www.baidu.com>把百度设为主页</a></p><p style=height:14px><a href=http://e.baidu.com>加入百度推广</a> | <a href=http://top.baidu.com>搜索风云榜</a> | <a href=/home.html>关于百度</a> | <a href=http://ir.baidu.com>About Baidu</a></p><p id=b>©2009 Baidu <a href=http://www.baidu.com/duty/>使用百度前必读</a> <a href=http://www.miibeian.gov.cn target=_blank>京ICP证030173号</a> <img src=http://gimg.baidu.com/img/gs.gif></p><map name=mp><area shape=rect coords="43,22,227,91" href=http://hi.baidu.com/baidu/ target=_blank title="点此进入 百度空间"></map></center></body><script>var w=document.f.wd;function s(o){if(w.value.length>0){var h=o.href;var q=encodeURIComponent(w.value);if(h.indexOf("q=")!=-1){o.href=h.replace(new RegExp("q=[^&$]*"),"q="+q)}else{o.href+="?q="+q}}};(function(){if(new RegExp("q=([^&]+)").test(location.search)){w.value=decodeURIComponent(RegExp.$1)}})();if(navigator.cookieEnabled && !/sug?=0/.test(document.cookie)){document.write('<script src=http://www.baidu.com/js/bdsug.js?v=1.1.0.1><\/script>')};window.onunload=function(){};</script><script>w.focus()</script></html><!--3f96fc2c3e866000-->
http://www.163.com/ 抓取文件第一次打开乱码,手动修改编码集后 正常显示
http://csdn.net/ 抓取文件第一次打开正常显示、
http://www.sina.com.cn/ 抓取文件第一次打开乱码,手动修改编码集后 正常显示用三楼的代码效果一样!那位硕说这是怎么回事?
希望都是http://csdn.net/ 的效果
http://www.163.com/ 抓取文件第一次打开乱码,手动修改编码集后 正常显示
http://csdn.net/ 抓取文件第一次打开正常显示、
http://www.sina.com.cn/ 抓取文件第一次打开乱码,手动修改编码集后 正常显示 用三楼的代码效果一样! 那位硕说这是怎么回事?
希望都是http://csdn.net/ 的效果