WebRequest.GetResponse()在有效的URl上返回404

时间:2014-05-02 11:46:16

标签: c# web httpwebrequest screen-scraping httpwebresponse

我正在尝试通过C#应用程序抓取网页,但它仍在不断响应

  

“远程服务器返回错误:(404)Not Found。”

网页可通过浏览器访问,但应用程序仍然失败。任何帮助表示赞赏。

var d = DateTime.UtcNow.Date;
var AddressString = @"http://www.booking.com/searchresults.html?src=searchresults&si=ai%2Cco%2Cci%2Cre%2Cdi&ss={0}&checkin_monthday={1}&checkin_year_month={2}&checkout_monthday={3}&checkout_year_month={4}";
var URi = String.Format(AddressString, "Prague", d.Day, d.Year + "-" + d.Month, d.Day + 1, d.Year + "-" + d.Month);
var request = (HttpWebRequest)WebRequest.Create(URi);
request.Timeout = 5000;
request.UserAgent = "Fiddler"; //I tried to set next three rows not to be null
request.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = WebProxy.GetDefaultProxy();
try
{
    var response = (HttpWebResponse)request.GetResponse();
}
catch(WebException e)
{
    var response = (HttpWebResponse)e.Response; //e.Response contains WebPage, but it is incomplete
    StreamReader sr = new StreamReader(response.GetResponseStream());
    HtmlDocument doc = new HtmlDocument();
    doc.Load(sr);
    var a = doc.DocumentNode.SelectNodes("div[@class='resut-details']"); //fails, as not all desired nodes arent in response
 }

编辑:

大家好,谢谢你的建议。

根据David Martins的回复,我添加了标题:“Accept-Encoding:gzip,deflate,sdch”,但它本身并没有帮助。

我使用Fidller尝试获取有关该问题的任何信息,但我第一次看到该应用程序并没有让我更聪明。另一方面,我尝试将request.UserAgent更改为我的浏览器发送的内容(“User-Agent:Mozilla / 5.0(Windows NT 6.1; WOW64)AppleWebKit / 537.36(KHTML,如Gecko)Chrome / 34.0.1847.131 Safari / 537.36“;)瞧,我不再获得404例外了,但是文件不可读,因为它充满了这样的字符:¿½½〜���G�。我尝试设置request.TransferEncoding =“UTF-8”,但要启用此属性,request.SendChunked必须设置为true,以

结尾
  

ProtocolViolationException

     

附加信息:无法为不写入数据的操作设置Content-Length或Chunked Encoding。

编辑2: 我忘记了什么,我无法弄清楚是什么。我正在以某种方式编码响应,需要首先解码它才能正确读取它。即使在Fiddler,当我想看到响应时,我需要确认解码以检查结果。在我用fiddler解码后,我得到了我想要进入我的应用程序...

1 个答案:

答案 0 :(得分:1)

所以,在尝试了Jon Skeet和David Martin的建议之后,我进一步找到了另一个地方,并在另一个问题中找到了新问题的相关答案。如果有人曾经找过类似的东西,那么答案就在这里:

.NET: Is it possible to get HttpWebRequest to automatically decompress gzip'd responses?