Python Forum

Full Version: Automate Google Search and Extract Top Result
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Problem:
Write a Python script using Selenium to:

Open Google.

Search for a specific query (e.g., "best python forum").

Extract and print the title of the first search result.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

def google_search_top_result(query):
    # Initialize WebDriver (make sure you have ChromeDriver installed)
    driver = webdriver.Chrome()
    driver.get("https://www.google.com")

    # Accept cookies if needed (some regions may show this popup)
    try:
        accept_btn = driver.find_element(By.XPATH, "//button[contains(text(),'Accept')]")
        accept_btn.click()
    except:
        pass  # If no popup, continue

    # Find search box and perform search
    search_box = driver.find_element(By.NAME, "q")
    search_box.send_keys(query + Keys.RETURN)
    time.sleep(2)

    # Get the title of the first search result
    first_result = driver.find_element(By.CSS_SELECTOR, "h3")
    print("Top search result:", first_result.text)

    # Optional: Close the browser
    driver.quit()

# Run the function with a search term
google_search_top_result("best python forum")
✅ Requirements:
Install Selenium: pip install selenium