DEV Community

Basil Ahamed
Basil Ahamed

Posted on

Automate Google Search with Python Selenium

Introduction
In today’s digital age, automation is key to streamlining repetitive tasks. One common task that can benefit from automation is performing a Google Image search and extracting links from the search results. In this article, we’ll explore how to automate Google Image searches using Python and Selenium.

Selenium is a popular library for automating web browsers, and we’ll use it to build a Python script that performs Google Image searches for a given query and extracts the links from the search results.

Prerequisites
Before we dive into the code, make sure you have the following prerequisites in place:

Python: You’ll need Python installed on your system.
Selenium: Install the Selenium library using pip: pip install selenium
Chrome WebDriver: Download the Chrome WebDriver for your Chrome browser version. Ensure that the WebDriver executable is in your system’s PATH or provide the path to it in the script.

Full-Code Implementation

from selenium import webdriver
from selenium.webdriver.common.by import By

class GoogleImageSearch:
    def __init__(self):
        self.driver = webdriver.Chrome()  # Initialize Chrome WebDriver

    def fetch_links_by_search(self, search_query):
        # Navigate to Google Images
        self.driver.get('https://www.google.com/imghp?hl=en')

        # Find the search bar and input the search query
        search_box = self.driver.find_element(By.NAME, "q")
        search_box.send_keys(search_query)
        search_box.submit()

        # Wait for search results to load (add any additional wait if required)
        self.driver.implicitly_wait(5)

        # Find all <a> elements with href containing "/imgres" (image result links)
        links = self.driver.find_elements(By.XPATH, "//a[contains(@href, '/imgres')]")

        # Extract and print the links
        for link in links:
            href_value = link.get_attribute('href')
            print(href_value)

        # Close the WebDriver
        self.driver.quit()

# Example usage: 
if __name__ == "__main__":
    search_query = "tech" 
    google_image_search = GoogleImageSearch()
    google_image_search.fetch_links_by_search(search_query)
Enter fullscreen mode Exit fullscreen mode

Running the Script
To use the script, change the search_query variable to your desired search term, and execute the script. It will open a Chrome browser, perform the Google Image search, and print the links to the console.

Conclusion
Automating Google Image searches with Python and Selenium can save you time and effort when you need to extract links from search results. This article provided you with the code and explained its functionality. With this knowledge, you can build upon it and adapt it to your specific automation needs. Also compare images through python selenium with visual-comparison module.

Top comments (0)