WebClient DownloadString没有返回任何内容。

6

我想从Pirate Bay的搜索查询中获得源代码,但是我在我的代码中使用这个功能并没有返回任何结果:

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

必须正常工作。你期望的结果是什么? - Hamlet Hakobyan
WebClient工作正常,如果您得到一个空字符串,那么很可能是URL错误。 - Aleksei Chepovoi
我的期望结果是从那个网页获取源代码,但实际上却得到了一个空字符串。 - Marcelo Cantú
你是否有防火墙或代理之类的东西可能导致出站连接失败,或将您重定向到另一个页面? - Sam Plus Plus
不,我没有防火墙、杀毒软件或其他任何东西。 - Marcelo Cantú
你试过我的更新了吗?它解决了你的问题...(如果是这样,你可以选择它作为答案)。 - Noctis
1个回答

12

这是一个快速测试:

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将返回一个空字符串,而谷歌则会提供你正在寻找的源代码。

编辑:正如我所料,你需要像Web浏览器一样标识自己。这可以通过你的查询实现:

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
@Noctis,你的在头部添加userAgent的解决方案对我来说完全有效。 - Haider Ali Wajihi
1
@HaiderAliWajihi 是的,因为你欺骗了海盗湾,让它认为你是一个浏览器 :). 很高兴能帮到你。 - Noctis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接