簡體   English   中英

如何解析來自谷歌的圖像並將它們顯示到圖片框中?

[英]How do I parse images from google and display them into a pictureBox?

我正在嘗試在 Windows 窗體中進行 Google 圖片搜索,即使我手動搜索 xPath,我的代碼也會返回 null,它會將我帶到圖片。 我對 API 和 NuGet 包還很陌生,所以對我來說輕松點,哈哈! 該錯誤特別是“對象引用未設置為對象的實例。 但是當我搜索 xPath 時,它會顯示 48 個結果。 這是我的代碼

private void searchButton_Click(object sender, EventArgs e)
    {
        string ImageQuery = titleTextBox.Text;
        var htmlDocument = new HtmlWeb().Load("https://www.google.com/search?q=+" + ImageQuery + "&tbm=isch");
        var imageNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='bRMDJf islir']/img");
        string imagePath = imageNode.Attributes["src"].Value;

        var imageStream = HttpWebRequest.Create(imagePath).GetResponse().GetResponseStream();
        this.optionOnePicture.Image = Image.FromStream(imageStream);
    }

您可以嘗試以下代碼從谷歌獲取圖像並將其顯示在圖片框中。

 private void button1_Click(object sender, EventArgs e)
        {
            string ImageQuery = textBox1.Text;
            var htmlDocument = new HtmlWeb().Load("https://www.google.com/search?q=+" + ImageQuery + "&tbm=isch");
            var list=GetImagesInHTMLString(htmlDocument.Text);
            var str = list[0];
            string pattern = @"(https://.*);";
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
            Match matches = rgx.Match(str);
            string path = matches.Groups[1].Value;
            var imageStream = HttpWebRequest.Create(path).GetResponse().GetResponseStream();
            this.pictureBox1.Image = Image.FromStream(imageStream);
        }

        private List<string> GetImagesInHTMLString(string htmlString)
        {
            List<string> images = new List<string>();
            string pattern = @"<(img)\b[^>]*>";
            Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = rgx.Matches(htmlString);

            for (int i = 0, l = matches.Count; i < l; i++)
            {
                images.Add(matches[i].Value);
            }
            return images;
        }

為了測試,我選擇了搜索后的第一張圖片。

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM