Search for image in HTML

1

In a form, I'll perform an image search on Bing (in the background) like this:

titulo.Text = "sou doador"
string minhaBusca = titulo.Text + " app";
minhaBusca = "http://www.bing.com/images/search?q=" + minhaBusca;

Then I want to get the source link from the first 3 images, for this I need to search the source code for: .jpg or .png . I know there is a pattern on the Bing page, that the image link is within a item div:

<div class="item"><a href="http://vmulher4.vila.to/interacao/4004739/doacao-de-sangue-eu-sou-um-doador-e-voce-57209-1.jpg" class="thumb" target="_blank" h="ID=images,5012.1">

How do I get the three links from href and store them in an array or variable? And to display them on my form?

    
asked by anonymous 20.09.2015 / 17:08

1 answer

1

First you need to install a NUGET package in your project, called HtmlAgilityPack - Nuget , which will help you in this !

After this the HtmlWeb of the code below will be available in your project for use.

Use as follows:

  <img src="valor da lista aqui dentro ex: http://tse4.mm.bing.net/th?id=OIP.Meea6e108be6309f544bab7a1....">

Code in C #:

titulo.Text = "sou doador";
string minhaBusca = titulo.Text + " app";
string url = "http://www.bing.com/images/search?q=" + minhaBusca;
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);


       var div = doc.DocumentNode.SelectSingleNode("//div[@class='imgres']"); //pega o que tendo dentro da div que tem a classe 'imgres'

        List<string> ListaImagens = new List<string>(); // cria a lista que vai guardar os links
        if (div != null) // verifica se a div achada anteriormente nao e nula.
        {

            foreach (HtmlNode type in div.Descendants("a")) // pego todos as tags <a> dentro da div, e percorre cada um (objeto type)
            {
                ListaImagens.Add(type.Element("img").Attributes["src2"].Value); //adiciono na lista o elemento 'img' dentro de 'a', e pego o valor do atributo 'src2' do elemento 'img'
            }
        }
        else
        {
            MessageBox.Show("Ops! Não retornou imagem nenhuma!");
        }

Remember to be using the following assemblies on top:

using HtmlAgilityPack; //do pacote nuget!
using System;
using System.Collections.Generic;
using System.Windows.Forms;

Values will be within the Image List list. Ai is just how I showed you in the HTML IMG tag example

    
21.09.2015 / 04:49