【问题标题】:WebClient DownloadString not returning anythingWebClient DownloadString 不返回任何内容
【发布时间】:2013-11-03 20:21:36
【问题描述】:

我想从海盗湾的搜索查询中获取源代码,我的代码中有这个,但它没有返回任何内容:

WebClient webpage = new WebClient();
string source=  webpage.DownloadString("http://thepiratebay.sx/search/documentary/0/99/0");

【问题讨论】:

  • 必须正常工作。你的预期结果是什么?
  • WebClient 工作正常,因为您得到一个空字符串,这可能是 url 错误
  • 我的预期结果是该网页的源代码,但它给我一个空字符串
  • 您是否有可能导致出站连接失败或将您重定向到另一个页面的防火墙或代理?
  • 不,我没有防火墙或防病毒软件或任何东西

标签: c# webclient downloadstring


【解决方案1】:

这是一个快速测试:

xaml:

<Label Content="{Binding ElementName=window_name, Path=SourceTest}"></Label>
<Label Content="{Binding ElementName=window_name, Path=SourceTest2}"></Label>

代码:

string source_url = "http://thepiratebay.sx/search/documentary";

WebClient webpage = new WebClient();
SourceTest = webpage.DownloadString(source_url);
if (SourceTest == "")
SourceTest = "stream was empty.";


source_url = "http://www.google.com";

webpage = new WebClient();
SourceTest2 = webpage.DownloadString(source_url);
if (SourceTest2 == "")
    SourceTest2 = "stream was empty.";

您的 URL 将返回一个空字符串,另一方面,Google 将为您提供您正在寻找的来源。

编辑: 正如我所假设的,您需要像网络浏览器一样进行识别。这适用于您的查询:

string source_url = "http://thepiratebay.sx/search/documentary/0/99/0";

using (var webpage = new WebClient())
{
    webpage.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
    SourceTest = webpage.DownloadString(source_url);
}

【讨论】:

  • 使用string source_url = "http://thepiratebay.sx/ 会起作用,所以我猜他们可能会过滤来自非浏览器的请求?
  • @Noctis 您在标头中添加 userAgent 的解决方案绝对适合我。
  • @HaiderAliWajihi 是的,因为你愚弄了海盗湾认为你是一个浏览器:)。很高兴它有帮助。
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2017-11-23
  • 1970-01-01
  • 2020-04-27
相关资源
最近更新 更多