简体   繁体   中英

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

I'm trying to make a Google Images search in windows forms, and my code is returning null even though if I manually search the xPath it takes me to the images. I'm rather new to API's and NuGet packs so go easy on me LOL! The error specifically is 'Object reference not set to an instance of an object. But when I search the xPath it shows 48 results. Here is my code

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);
    }

You could try the following code to get images from google and show it in the picturebox.

 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;
        }

In order to test, I selected the first picture after the search.

Result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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