我正在尝试下载一个网站的内容。但是对于某个网页,返回的字符串包含了许多乱码字符,其中包括很多�字符。
以下是我最初使用的代码。
我还尝试使用WebClient的其他实现方式,但结果仍然相同:
以下是我最初使用的代码。
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = "GET";
req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(source);
我还尝试使用WebClient的其他实现方式,但结果仍然相同:
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
using (WebClient client = new WebClient())
using (var read = client.OpenRead(url))
{
doc.Load(read, true);
}
从搜索结果来看,我猜测这可能与编码有关,因此我尝试了下面发布的两个解决方案,但仍无法使其正常工作。
- http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx
- http://bytes.com/topic/c-sharp/answers/653250-webclient-encoding
无法下载的网站是维基百科英文版(en . wikipedia . org / wiki / United_States)上的 United_States 文章,虽然我尝试过其他维基百科文章,但没有出现此问题。