gpt4 book ai didi

C# 使用 C# WebClient 或 HttpWebRequest 将网站下载到字符串中

转载 作者:太空狗 更新时间:2023-10-29 21:35:57 27 4
gpt4 key购买 nike

我正在尝试下载网站的内容。但是对于某个网页,返回的字符串包含困惑的数据,包含许多 � 字符。

这是我最初使用的代码。

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);
}

通过搜索我猜想这可能是编码的问题,所以我尝试了下面发布的两种解决方案,但仍然无法正常工作。

我似乎无法下载的违规网站是英文版维基百科 (en . wikipedia . org/wiki/United_States) 上的 United_States 文章。虽然我已经尝试了很多其他维基百科文章,但没有看到这个问题。

最佳答案

使用 HtmlAgilityPack 中的内置加载器对我有用:

HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://en.wikipedia.org/wiki/United_States");
string html = doc.DocumentNode.OuterHtml; // I don't see no jumbled data here

编辑:

将标准 WebClient 与您的用户代理一起使用将导致 HTTP 403 - 禁止 - 使用它对我有用:

using (WebClient wc = new WebClient())
{
wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4");
string html = wc.DownloadString("http://en.wikipedia.org/wiki/United_States");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
}

另请参阅此 SO 线程:WebClient forbids opening wikipedia page?

关于C# 使用 C# WebClient 或 HttpWebRequest 将网站下载到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7518119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com