Google Search Scraper with Cookie Handling and CAPTCHA Bypass
Here's a Python script that automates Google search for "stellar blade nikke dlc", handles cookies, attempts to bypass CAPTCHA, and extracts the top 10 search results with their metadata:
import time
import random
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import undetected_chromedriver as uc
def setup_driver():
options = uc.ChromeOptions()
options.add_argument("--start-maximized")
options.add_argument("--disable-notifications")
options.add_argument("--disable-infobars")
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--no-sandbox")
# Add user agent to make it look more like a real browser
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
driver = uc.Chrome(options=options)
return driver
def handle_cookies(driver):
try:
# Wait for cookie banner to appear (if it does)
cookie_banner = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.ID, "L2AGLb"))
)
# Click the "Accept all" button
accept_button = driver.find_element(By.XPATH, "//button[contains(text(), 'Accept all')]")
accept_button.click()
print("Accepted cookies")
except (NoSuchElementException, TimeoutException):
print("No cookie banner found or couldn't accept cookies")
def search_google(driver, query):
driver.get("https://www.google.com")
time.sleep(2) # Wait for page to load
# Handle cookies if they appear
handle_cookies(driver)
# Find the search box and enter the query
search_box = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "q"))
)
search_box.clear()
search_box.send_keys(query)
search_box.send_keys(Keys.RETURN)
print(f"Searching for: {query}")
# Wait for results to load
time.sleep(3)
def bypass_captcha(driver):
try:
# Check for CAPTCHA elements
captcha_frame = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.XPATH, "//iframe[contains(@src, 'captcha')]"))
)
print("CAPTCHA detected! Attempting to bypass...")
# Try to click on the CAPTCHA checkbox (this is a simple approach)
try:
checkbox = driver.find_element(By.XPATH, "//div[@role='checkbox']")
checkbox.click()
print("Clicked CAPTCHA checkbox")
except NoSuchElementException:
print("Couldn't find CAPTCHA checkbox")
# Sometimes refreshing helps
driver.refresh()
time.sleep(3)
except (NoSuchElementException, TimeoutException):
print("No CAPTCHA detected")
def extract_search_results(driver):
results = []
# Wait for results to load
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "div.g"))
)
# Find all search result containers
result_containers = driver.find_elements(By.CSS_SELECTOR, "div.g")
for i, container in enumerate(result_containers[:10]): # Limit to top 10
try:
# Get the position (1-based index)
position = i + 1
# Get the URL
link = container.find_element(By.CSS_SELECTOR, "a")
url = link.get_attribute("href")
# Get the title
title = link.text
# Get the domain
domain = url.split("//")[-1].split("/")[0]
# Get the meta description (if available)
description_element = container.find_elements(By.CSS_SELECTOR, "div.IsZvec")
description = description_element[0].text if description_element else "No description available"
results.append({
"position": position,
"title": title,
"domain": domain,
"url": url,
"description": description
})
except Exception as e:
print(f"Error processing result {i+1}: {str(e)}")
continue
return results
def main():
query = "stellar blade nikke dlc"
# Set up the driver
driver = setup_driver()
try:
# Perform the search
search_google(driver, query)
# Check for CAPTCHA
bypass_captcha(driver)
# Extract results
results = extract_search_results(driver)
# Print the results
print("\nTop 10 Search Results:")
for result in results:
print(f"\nPosition: {result['position']}")
print(f"Title: {result['title']}")
print(f"Domain: {result['domain']}")
print(f"URL: {result['url']}")
print(f"Description: {result['description']}")
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
# Close the browser
driver.quit()
if __name__ == "__main__":
main()
Important Notes:
-
CAPTCHA Bypass: This script attempts a simple CAPTCHA bypass by clicking the checkbox. Google's CAPTCHA is sophisticated and may still block automated access. For reliable CAPTCHA solving, you would need a CAPTCHA solving service.
-
undetected_chromedriver: This script uses undetected_chromedriver which is better at avoiding detection than regular Selenium. You'll need to install it with:
pip install undetected-chromedriver
-
Legal Considerations: Automating Google searches may violate Google's Terms of Service. Use this for educational purposes only.
-
Dependencies: You'll need to have Chrome installed on your system.
-
Rate Limiting: Google may block your IP if you make too many requests in a short time.
-
Alternative Approach: For a more reliable solution, consider using the official Google Custom Search JSON API, which provides structured data without needing to scrape the page.
Would you like me to modify any part of this script to better suit your needs?