0 notas0% acharam este documento útil (0 voto) 35 visualizações6 páginasImagens de Raspagem Da Web Com Python e
Imagens de raspagem da Web com Python e
Direitos autorais
© © All Rights Reserved
Levamos muito a sério os direitos de conteúdo. Se você suspeita que este conteúdo é seu,
reivindique-o aqui.
Formatos disponíveis
Baixe no formato PDF ou leia on-line no Scribd
B Imagens de raspagem da Web
Imagens de raspagem da Web com Python e
Selenium
Como raspar e capturar imagens em sites.
Foto por Toa Heftiba on Unspiash
Se vocé quisesse treinar um modelo com base em diferentes tipos de imagens, precisaria obter muitas
imagens. Vocé poderia obter as imagens manualmente, mas isso exigiria muito tempo e esforgo. Uma maneira
mais eficiente de obter imagens é raspar as imagens das paginas da web. A raspagem da Web fornece uma
maneira facil de obter uma grande quantidade de dados em um perfodo de tempo relativamente curto.
Neste artigo, criaremos um script que ird raspar uma pagina da Web do Google, extrair algumas imagens e
criar conjuntos de dados. As etapas @ seguir serdo executadas usando Python e Selenium,
1. Instale o pacote Selenium.
2. Importe as bibliotecas.
3. Instale o driver da Web.
4. Inicie 0 navegador e abra o URL.
5. Carregue as imagens.
6. Revise a estrutura HTML da pagina da Web.
7. Encontre e extraia imagens.
8, Baixe imagens.
Instale o pacote Selenium
!pip instalar selénioSelenium é uma biblioteca python que pode coletar dados em sites dinamicamente. Também pode ser usado
para automagdo e teste da web. A extragao de dados da web é apenas uma pequena parte da biblioteca
selénio. Alguns dos recursos do Selenium incluem:
‘+ Compatibilidade com varios navegadores
‘+ Suporte a varios idiomas
‘+ Manipulagdo de elementos dindmicos da Web
+ Elementos da Web faceis de identificar
+ Velocidade e desempenho
‘+ Cédigo aberto e portatil
Importar as bibliotecas
Importar solicitagées do Selenium Inportar Webdriver do [Link] .[Link] impor
+ requests permite que vocé envie solicitages HTTP para um servidor web que retorna um objeto de
resposta com todos os dados de resposta (i.e. HTML).
‘+ WebDriver aciona 0 navegador de varias maneiras, como carregar paginas, alternar para diferentes
janelas/quadros e obter titulos de paginas.
‘* urllib 6 um pacote que contém varios médulos para trabalhar com URLs, como abrir e ler URLs.
‘+ A fungdo time é usada para contar 0 ntimero de segundos decorridos desde a época.
Instale o driver da Web
lapt-get update
fapt install chromium-chromedriver
chrome_options = webdriver .chromeOptions() chrome_options.add_argument(’--headless') chrom
O driver da web é um componente chave do selénio. O driver da Web é uma estrutura de automacao do
navegador que funciona com APIs de cédigo aberto. A estrutura opera aceitando comandos, enviando esses
‘comandos para um navegador e interagindo com aplicativos.
© Selenium oferece suporte a varios navegadores da Web e oferece drivers da Web para cada navegador. Eu
importel o driver da web do Chrome do selenium. Como alternativa, vocé pode baixar o driver da Web para
seu navegador especifico e armazené-lo em um local onde possa ser facilmente acessado
(C:users\webdriver\[Link]). Vocé pode baixar um driver da web para 0 seu navegador neste link:
[Link]
to%20interface%2OwithInicie o navegador e abra o URL
Crie uma varidvel de url contendo a pagina da Web para uma pesquisa de imagens do Google.
url = (“[Link]
{s}&tbm=isch&tbs=surk3Aafc&hl=en&ved=@CATQpwVqFWwoTCKCalc6s4-
OCFQAAAAAGAAAAABACEbiw=1251&bih=568" )
Launch the browser and open the given ur in your webdriver. We format the url in our search by adding a
search word in place of “s” In this case, we have formatted the value of s to be "Pets".
driver .get([Link](s='Pets’))
Load the Images
The execute script function will scroll down the body of the web page and load the images. This function will
insure that each time we load a page, it goes to the end of the webpage. We have given 5 seconds for the
images to load in order to provide enough time for image rendering.
driver .execute_script( "window. scrollTo(@, document .[Link])
tine .sleep(5)
Review the Web Page's HTML Structure
We need to understand the structure and contents of the HTML tags and find an attribute that is unique only t
q=pets&tbm-=isch&ved=2ahUKEwiWjr_P3IrSAhWKHzQIHSKyC11Q2-
oCegQIABAARog=pets&gs_Icp=CgNpbWcQAzIECCMQJzlICAAQgAQQsQMyBwgAELEDEEMyBwgAELEDEEMyB
‘qnZYpapM4q_OPEPouSukAU&bih=S68&biw=12518hI
We will now go to the url and find the attributes that are related to images. Access the webpage and right-
click anywhere on the web page, select inspect from the drop-down list, click the arrow icon on the upper
left-hand side of the screen with the HTML and then click an image on the webpage. This will result in the
following screen being displayed.
On the HTML screen, you will see highlighted the HTML line containing the attributes related to the selected
image. We find that the class = "rg_i Q4LuWa",If you move the cursor over other images on the web page you will see a pattern where all of the classes
contain the values “Q4LuWa"
‘So, we want to find and extract the objects where class contains the values "@4LuWe"
Find and Extract Images
We will use the find_elements_by_xpath() function to identify the images.
imgResults = driver. find_elements([Link], "//img[contains(@class, ‘Q4Luitd" )]")
All of the images that contained “@4LuWD" in the class name are now stored in imgResults which is a
selenium object. If you display the imgResults you will only see a description of the selenium object.
Now we need to download the images. To retrieve an image we need to access the “src” attribute. The value
of the src attribute is a URL that will open the image on a new page where we will use python functions to
download the image.
We will use the image_object.get_attribute('src’) function to access the scr attribute. The getattribute
function returns the attribute value of the parameter sent as an argument.
sre = []
for img in imgResults:
[Link](img.get_attribute('src'))
The src list contains the list of image URL's. We will now go through the list and use a python function to
download the images.
Download Images
for 4 in range(19):
urllib. request .urlretrieve(str(sre[i]), “sample_data/pets{}. jpg” -format(i))
The loop will run 10 times and download 10 images to your file folder. You can specify a higher number if you
need more images.
The [Link]() function has two arguments. The first is a URL, and the second is the file path
where you want to store the downloaded image. Each image will be stored in a separate file.
The downloaded images are stored in your specified file folder.We have combined the image files into a single PDF file shown below.
This article shows how you can easily scrape and capture images on a website.
Thanks so much for reading my article! If you have any comments or feedback, please let me know.
If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a
Medium member. Membership gives you unlimited access to all articles on Medium. You can sign up using this
link [Link]