从网站下载数据时出现问题

本文关键字:问题 数据 网站 下载 | 更新日期: 2023-09-27 17:58:40

基本上我没有下载网页的经验,我正试图获得这个每天都有股票交易价格的页面,但运气不佳。我不确定是我做错了什么,还是网络服务器拒绝了这种请求。网站使用铬或IE.

               using (WebClient client = new WebClient())
           {
               byte[] response = client.DownloadData("http://limun.hr/main.aspx?id=18");
               string result = System.Text.Encoding.UTF8.GetString(response);
           }

如有任何帮助,我们将不胜感激。

编辑:我忘了把错误包括在内。返回的字符串只包含一个字符-@。

从网站下载数据时出现问题

一些网站会查看HTTP标头中的UserAgent字符串,以查看调用方是否是实际的web浏览器。如果使用HttpWebRequest类,则可以对调用进行更多控制,并且可以伪造UserAgent字符串来模拟真实的web浏览器。尝试以下方法使其工作:

HttpWebRequest request = WebRequest.Create("http://limun.hr/main.aspx?id=18") as HttpWebRequest;
request.UserAgent = "Mozilla /5.0 (Compatible MSIE 9.0;Windows NT 6.1;WOW64; Trident/5.0)";
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(););
string content = reader.ReadToEnd();
reader.Close();
response.Close();
Console.WriteLine(content);

问题确实是HTTP标头中的UserAgent字符串错误,但您可以使用WebClient类将该字符串添加到标头中,并使代码更简单:

        using (WebClient client = new WebClient())
        {
            client.Headers.Add("user-agent", "Mozilla /5.0 (Compatible MSIE 9.0;Windows NT 6.1;WOW64; Trident/5.0)");
            string res = client.DownloadString("http://limun.hr/main.aspx?id=18");
            Console.WriteLine(res);
        }

注意WebClient还有一个DownloadStringTaskAsync方法,根据您的需要,您可能会觉得它很有用。