110,535
社区成员
发帖
与我相关
我的任务
分享
//调用
GetHtml("http://www.soso.com/q?pid=s.idx&cid=s.idx.se&w=%D1%B5%C1%B7%CB%FE");
public string GetHtml(string url)
{
//判断网页编码
Encoding wCode;
string PostPara = "";
CookieContainer CookieCon = new CookieContainer();
HttpWebRequest wReq;
wReq = (HttpWebRequest)WebRequest.Create(@url);
wReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215;)";
Match a = Regex.Match(url, @"(http://).[^/]*[?=/]", RegexOptions.IgnoreCase);
string url1 = a.Groups[0].Value.ToString();
wReq.Referer = url1;
wReq.Method = "GET";
//设置页面超时时间为12秒
wReq.Timeout = 12000;
HttpWebResponse wResp = (HttpWebResponse)wReq.GetResponse();
System.IO.Stream respStream = wResp.GetResponseStream();
string strWebData = "";
try
{
string cType = wResp.ContentType.ToLower();
Match charSetMatch = Regex.Match(cType, "(?<=charset=)([^<]*)*", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string webCharSet = charSetMatch.ToString();
wCode = System.Text.Encoding.GetEncoding(webCharSet);
}
catch
{
wCode = Encoding.Default;
}
if (wResp.ContentEncoding == "gzip")
{
GZipStream myGZip = new GZipStream(respStream, CompressionMode.Decompress);
System.IO.StreamReader reader;
reader = new System.IO.StreamReader(myGZip, wCode);
strWebData = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
else
{
System.IO.StreamReader reader;
reader = new System.IO.StreamReader(respStream, wCode);
strWebData = reader.ReadToEnd();
reader.Close();
reader.Dispose();
}
// this.m_WebpageSource = strWebData;
return strWebData;
}
不是。字符串编码我搞清楚了 我想问的 是为什么 StreamReader 遇到特殊符号就 停了,看看有什么过滤的方法或者 什么办法让我把搜搜的排名 获取到就行了 我想知道 你在问什么 字符串编码问题?
我想知道 你在问什么 字符串编码问题?
百科裏面的html是不是中間故意設置了終止符>或者 -->
路过,学习,看到二楼的方法很好
// 获取网页的HTML内容,根据网页的charset自动判断Encoding public string GetHtml(string url) { return GetHtml(url, null); } // 获取网页的HTML内容,指定Encoding public 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 public 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; } } //以上方法应该是目前最优的