Home > Back-end >  Webscraping to extract all pages from MercadoLivre
Webscraping to extract all pages from MercadoLivre

Time:08-30

I am trying to get list of all products from mercado livre ,but I dont know what else to write in my code. My code is running fine ... The only thing that I need is to extract products from all pages instead of page one.

Follow code bellow:

import csv
from csv import reader, writer
import requests
from bs4 import BeautifulSoup

url_base = 'https://lista.mercadolivre.com.br/'

produto_nome = input('Qual produto você deseja? ')

response = requests.get(url_base   produto_nome)

site = BeautifulSoup(response.text, 'html.parser')

produtos = site.findAll('div', attrs={'class': 'andes-card andes-card--flat andes-card--default ui-search-result ui-search-result--core andes-card--padding-default'})


with open (r'C:\Users\Lucas\output\lista_precos.csv','a',encoding='utf8',newline='') as f:
    fieldnames = ['Produto','Link do Produto','Preco']
    
    dw = csv.DictWriter(f,delimiter=';',fieldnames=fieldnames)
    dw.writeheader()
       
    for produto in produtos:
        
        titulo = produto.find('h2', attrs={'class': 'ui-search-item__title'})
        link = produto.find('a', attrs={'class': 'ui-search-link'})
        real = produto.find('span', attrs={'class': 'price-tag-fraction'})
        centavos = produto.find('span', attrs={'class': 'price-tag-cents'})

        print(produto.prettify())
        print('Título do produto:', titulo.text)
        print('Link do produto:', link['href'])


        if (centavos):
            print('Preço do produto: R$', real.text   ','   centavos.text)
            
        else:
            print('Preço do produto: R$', real.text)
                  
        linha = titulo.text   ';'   link['href']   ';'   "R$"   real.text    ","   centavos.text   '\n'
        
        f.write(linha)
        
        print('\n\n')

CodePudding user response:

This example shows how to parse next pages (just find "Next page" link, if it doesn't exist break from the loop):

import requests
from bs4 import BeautifulSoup

url_base = "https://lista.mercadolivre.com.br/"
query = "vinho"

soup = BeautifulSoup(requests.get(url_base   query).content, "html.parser")

i = 1
while True:
    for tag in soup.select(".ui-search-item__title"):
        print(i, tag.text)
        i  = 1

    next_link = soup.select_one(
        "a.andes-pagination__link:-soup-contains(Seguinte)"
    )
    if not next_link:
        break

    soup = BeautifulSoup(requests.get(next_link["href"]).content, "html.parser")

Prints product titles from all the pages (40):


...

2010 Vinho Tinto Carnivor Cabernet Sauvignon 
2011 Vinho Tinto Portugues Velha Arvore 750ml Importado Orignal
2012 Vinho De Mesa San Martin Branco Niagara Suave 750ml Nacional
2013 Kit 2 Vinhos Concha Y Toro Carménère 750ml
2014 Vinho Tinto Merlot Bag In Box 5 Litros
2015 Espumante Brasileiro Rosé Demi-Sec Garibaldi Vero Trebbiano Malvasia Ancellotta Serra Gaúcha Garrafa 750ml
2016 Kit 2 Vinhos Casillero Del Diablo Cabernet Sauvignon  750ml
2017 Vinho Brasileiro Tinto Seco Chalise Serra Gaúcha Garrafa 750ml
2018 Vinho Manos Negras Artesano Malbec 2018 Tinto Argentina
2019  Vinho Casa Ferreirinha Esteva Tinto 750ml (6und)
2020 Vinho branco seco Uvas Diversas Collina adega Nova Aliança 750 ml
2021 Vinho Argentino Tinto Malbec Tolentino Garrafa 750ml

CodePudding user response:

If you want to get all the products in the system, you need to access other pages through pagination at the bottom of the page and run the product collection code.

For this I recommend you to use the Scrapy framework.

You can see an example here

  • Related