繁体   English   中英

无法通过 HttpWebRequest 获取 HTML 代码

[英]Can't get HTML code through HttpWebRequest

我正在尝试解析http://odds.bestbetting.com/horse-racing/today页面的 HTML 代码,以便获得比赛列表等。问题是我无法检索 Z74C4ZDBAD5FCAED038AAAFAF1C页面的代码。 这是function的C#代码:

    public static string Http(string url) {          
            Uri myUri = new Uri(url);
            // Create a 'HttpWebRequest' object for the specified url. 
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
            myHttpWebRequest.AllowAutoRedirect = true;
            // Send the request and wait for response.
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            var stream = myHttpWebResponse.GetResponseStream();
            var reader = new StreamReader(stream);
            var html = reader.ReadToEnd();
            // Release resources of response object.
            myHttpWebResponse.Close();

            return html;
    }

当我执行调用 function 的程序时,它会引发异常

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

这是:

无法处理从 HTTP/HTTPS 协议到其他不同协议的重定向。

我已经阅读了这个问题,但我似乎没有同样的问题。 我也尝试过用提琴手来嗅探流量,但看不到任何东西重定向到它重定向的地方或类似的东西。 我刚刚提取了这两个可能的重定向:odds.bestbetting.com/horse-racing/2011-06-10/byCourse 和odds.bestbetting.com/horse-racing/2011-06-10/byTime,但查询它们会产生结果与上述相同。

这不是我第一次做这样的事情,但我真的很迷茫。 有什么帮助吗?

谢谢!

我终于找到了解决方案......它实际上是标题的问题,特别是用户代理的问题。

经过大量搜索后,我发现在同一个站点上遇到与我相同问题的人。 尽管他的代码不同,但重要的是他手动将请求的 UserAgent 属性设置为浏览器的属性。 我想我以前做过这个,但我可能做得很糟糕......对不起。

如果有人感兴趣,最终代码是这样的:

    public static string Http(string url) {
        if (url.Length > 0)
        {
            Uri myUri = new Uri(url);
            // Create a 'HttpWebRequest' object for the specified url. 
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
            // Set the user agent as if we were a web browser
            myHttpWebRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4";

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            var stream = myHttpWebResponse.GetResponseStream();
            var reader = new StreamReader(stream);
            var html = reader.ReadToEnd();
            // Release resources of response object.
            myHttpWebResponse.Close();

            return html;
        }
        else { return "NO URL"; }
    }

非常感谢您的帮助。

您的问题可能有十几个可能的原因。

其中之一是来自服务器的重定向指向 FTP 站点或类似的站点。

也可能是服务器需要您未能提供的请求中的某些标头。

检查浏览器将发送到站点的内容并尝试复制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM