C#HttpWebRequest无法使用Bing图像

时间:2018-05-07 16:52:01

标签: c# httpwebrequest

我正在尝试使用浏览器获得的C#代码获得相同的HTTP响应。当我使用浏览器搜索“板块进行机械计算”时,我得到了大量的图片,但是当我删除我的'bing'浏览cookie并使用C#代码下载HTTP响应时,我得到零图片结果。有没有人知道如何使用C#代码获得与Bing图像相同的结果? Bing搜索API不是一个选项。

        private void button1_Click(object sender, EventArgs e)
    {
        string search = "plate for mechanical calculation";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.bing.com/images/search?q=" + search + "&qft=+filterui:license-L1&FORM=IRFLTR");

        request.AllowAutoRedirect = false;
        request.UserAgent = ".NET Framework ";
        request.Accept = "*/*";
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        request.Timeout = (int)Math.Round(10.0 * 1000);
        request.Method = "GET";
        request.ContentType = "application/x-www-form-urlencoded";
        request.CookieContainer = new CookieContainer();


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);
        string responseFromServer = reader.ReadToEnd();

        reader.Close();
        dataStream.Close();
        response.Close();

        File.WriteAllText(@"C:\Users\Klemen\Desktop\sourceCode.html", responseFromServer);

        MessageBox.Show("The End.");
    }

1 个答案:

答案 0 :(得分:0)

我更改了以下行,并在返回的html中得到了结果:     HttpWebRequest request =(HttpWebRequest)WebRequest.Create(“https://www.bing.com/images/search?q=”+ search);

图像位于生成的html中,例如:

<img height="170" width="230" src="https://tse2.mm.bing.net/th?id=OIP.4OY77AT9EcfuUutKYFdzIwHaLe&amp;w=230&amp;h=170&amp;rs=1&amp;pcl=dddddd&amp;o=5&amp;pid=1.1" alt=" " />

您需要解析图像标记,然后逐个获取图像结果。我建议您使用API​​而不是抓取。