How to Scrape Google Search Results Data using Mechanicalsoup

QS blog-02

Web scraping is the process of extracting data from websites automatically. It is a powerful technique that allows you to gather large amounts of data quickly and efficiently. In this blog post, we’ll learn how to scrape Google Search results data using the Mechanicalsoup library in Python.

Prerequisites

Before we start, you’ll need to have the following installed on your system:

  • Python 3.x
  • Mechanicalsoup library
  • BeautifulSoup4 library
  • Requests library

You can install these libraries using pip:

pip install mechanicalsoup
pip install beautifulsoup4
pip install requests

Step 1: Import the Required Libraries

import mechanicalsoup
import requests
from bs4 import BeautifulSoup
import csv
import json

Step 2: Connect to the Website

# Connect to Website
browser = mechanicalsoup.StatefulBrowser()
access_token = '6JrJjz0MVZ7EBN584a' # Access token from app.quickscraper.co
url = f"https://api.quickscraper.co/parse?access_token={access_token}&url=https://www.google.com/search?q=laptop&rlz=1C1CHBF_enIN979IN979&oq=laptop&gs_lcrp=EgZjaHJvbWUqDAgAEEUYOxixAxiABDIMCAAQRRg7GLEDGIAEMgYIARBFGEAyDQgCEAAYgwEYsQMYgAQyCggDEAAYsQMYgAQyDQgEEAAYgwEYsQMYgAQyBggFEEUYPTIGCAYQRRg8MgYIBxBFGDzSAQc5NTVqMGo3qAIAsAIA&sourceid=chrome&ie=UTF-8"
page = browser.get(url)

Note: In the provided code, we’re using the api.quickscraper.co service to bypass Google’s anti-scraping measures. You’ll need to replace the access_token value with your own token from the service.

Step 3: Parse the HTML

# Parse HTML
soup = BeautifulSoup(page.content, 'html.parser')
items = soup.find_all('div', class_=['g', 'Ww4FFb', 'vt6azd', 'asEBEc', 'tF2Cxc'])

Step 4: Extract the Search Results Data

google_search_items = []

for item in items:
    title = item.find('h3', class_=['LC20lb', 'MBeuO', 'DKV0Md']).text.strip() if item.find('h3', class_=['LC20lb', 'MBeuO', 'DKV0Md']) else None
    desciption = item.find('div', class_=['VwiC3b', 'yXK7lf', 'lVm3ye', 'r025kc', 'hJNv6b', 'Hdw6tb']).text.strip() if item.find('div', class_=['VwiC3b', 'yXK7lf', 'lVm3ye', 'r025kc', 'hJNv6b', 'Hdw6tb']) else None
    url_element = item.find('a', {'jsname': 'UWckNb'})
    url = url_element.get('href') if url_element else None

    foundItem = {
        "title": title,
        "desciption": desciption,
        "url": url,
    }

    google_search_items.append(foundItem)

Step 5: Save the Data to a JSON File

with open("google_search_items.json", "w") as file:
    json.dump(google_search_items, file, indent=4)

Conclusion

Congratulations! You’ve learned how to scrape Google Search results data using the Mechanicalsoup library in Python. This technique can be useful for various purposes, such as data analysis, market research, or content aggregation. However, it’s essential to respect website terms of service and use web scraping responsibly.

Remember to replace the access_token value with your own token from the app.quickscraper.co service, as using the provided token may result in errors or rate limiting.

Happy scraping!

Related Articles

Legiano Casino:Guía Completa para jugadores en España

Legiano Casino se ha consolidado como una opción atractiva para jugadores españoles que buscan variedad, seguridad y promociones competitivas. En esta guía te explicamos por qué merece la pena considerarlo, qué tipos de juego ofrece y cómo aprovechar sus ventajas desde el primer inicio de sesión. Si deseas visitar la

Read Article

Casinia Casinos — kompleksowy przewodnik dla polskich graczy

Casinia Casinos zyskuje coraz większą popularność wśród polskich graczy dzięki szerokiej ofercie gier, przejrzystym warunkom i atrakcyjnym promocjom. W tym artykule omówimy najważniejsze aspekty platformy: bonusy, metody płatności, dostępność mobilną, bezpieczeństwo oraz praktyczne wskazówki, które pomogą maksymalizować przyjemność z gry przy minimalnym ryzyku. https://casinia-casinos.pl to punkt wyjścia dla każdego, kto

Read Article

Najlepsze kasyno online w Polsce: jak wybrać bezpieczne i opłacalne miejsce do gry

Rynek kasyn online w Polsce rozwija się dynamicznie, a gracze szukają miejsc oferujących atrakcyjne bonusy, uczciwe warunki i bogatą ofertę gier. Wybór odpowiedniego kasyna ma kluczowe znaczenie dla doświadczenia i bezpieczeństwa — warto zwracać uwagę na licencję, metody płatności oraz opinie innych użytkowników. Jeżeli chcesz sprawdzić przykład platformy z klarownymi

Read Article

Przewodnik po bezpiecznym graniu w kasynie online

Wybór właściwego kasyna online może być trudny, zwłaszcza gdy rynek oferuje wiele platform różniących się promocjami, ofertą gier i warunkami wypłat. Warto zrozumieć, na co zwracać uwagę, aby gra była przyjemnością, a nie źródłem frustracji i ryzyka finansowego. Jeśli szukasz szybkiego źródła informacji o popularnych operatorach, regulacjach i opiniach graczy,

Read Article

Ivibet Polska: Kompletny przewodnik po kasynie online

Ivibet to platforma kasynowa, która zdobywa popularność wśród polskich graczy dzięki szerokiej ofercie slotów, atrakcyjnym bonusom i nowoczesnemu interfejsowi. W tym artykule przyjrzymy się najważniejszym aspektom serwisu, takim jak oferta gier, bezpieczeństwo, metody płatności oraz porady dotyczące odpowiedzialnej gry. Jeśli chcesz szybko rozpocząć rozgrywkę i sprawdzić dostępne promocje, skorzystaj z

Read Article

Plinko Casino w Polsce — przewodnik po popularnej grze kasynowej

Plinko to dynamiczna gra zręcznościowa, która zdobyła popularność wśród graczy online dzięki prostym zasadom i emocjonującym rozstrzygnięciom. W Polsce rośnie zainteresowanie tytułami typu Plinko, zwłaszcza tam, gdzie oferowane są atrakcyjne bonusy i przejrzyste warunki wypłat. Ten artykuł wyjaśnia, jak działa Plinko, jakie strategie warto rozważyć oraz na co zwracać uwagę

Read Article

Get started with 1,000 free API credits.

Get Started For Free

Copyright All Rights Reserved ©

Plongez dans l’univers moderne de Nine Casino, avec une interface intuitive et des jeux soigneusement sélectionnés pour maximiser le plaisir et les gains.

Découvrez la variété des jeux sur Simsino Casino, offrant une expérience immersive grâce à ses machines à sous et ses tables en direct innovantes.

Entrez dans l’univers raffiné de AlexanderCasino, avec des bonus attractifs, un design élégant et des promotions régulières pour fidéliser les joueurs.

Laissez-vous séduire par l’expérience de Bruno Casino, combinant sécurité, interface conviviale et opportunités de gains exceptionnelles.

Explorez la fiabilité et le professionnalisme de Legiano Casino, avec un large choix de jeux et un service client attentif pour un divertissement sécurisé.

Plongez dans le monde captivant de Casino Extra, où chaque session de jeu est enrichie par des jackpots progressifs et des promotions attractives.

Vivez l’expérience immersive de NV Casino, combinant diversité des jeux, sécurité et offres promotionnelles régulières.

Découvrez l’univers dynamique de Bet On Red, offrant un large éventail de jeux et des bonus généreux pour tous les amateurs de casinos en ligne.

💥 FLASH SALE: Grab 30% OFF on all monthly plans! Use code: QS-ALNOZDHIGQ. Act fast!