我试图下载网站的内容。但是,对于某个网页,返回的字符串包含混乱的数据,其中包含许多 字符。C#使用C#WebClient或HttpWebRequest将网站下载到字符串中
这是我最初使用的代码。
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);
我也试过可选的实施方式与Web客户端,但还是同样的结果:
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
违规的网站,我似乎无法下载是维基百科的英文版本的美国的文章(恩。维基百科。组织/维基/美国)。 虽然我已经尝试了一些其他wikipedia文章,并没有看到这个问题。
你不应该手动做这个,这是建立在已经,即看到这个答案:http://stackoverflow.com/questions/2973208/automatically-decompress-gzip-response-via-webclient-downloaddata – BrokenGlass
@BrokenGlass感谢您的提示。我已经想知道为什么我以前从未遇到过使用gzip编码的问题。 – Peter
谢谢,这对我有用! – EnISeeK