How to Build a Google AI Overview Scraper in Python

Google AI Overviews are AI-generated summaries in search results, and they are hard to collect because they do not appear for every query and often load after the page does. This tutorial builds a Python extractor that uses Playwright to render and expand the overview and BeautifulSoup to save its summary text and cited links as JSON. Every step runs on sample HTML pages we provide, not on live Google results. The script reports a status for each outcome, such as success, partial, or not detected, because overviews do not appear for every query and often load late. We also set up a Byteful residential proxy with a sticky session and verify its exit IP for authorized live collection.
With AI Overviews influencing search results, it's important to monitor AI-generated responses and their references. However, it can be harder to extract this data than to collect regular search results. Not all queries will have an AI Overview, and the dynamically generated overview content may be hard to extract. These elements can be identified, and the relevant information can be collected using a Python scraper implemented with Playwright and BeautifulSoup.
In this guide, you'll learn how to create a Google AI Overview scraper in Python, set up proxies for authorized requests, and generate structured JSON data containing AI-generated overviews and citations, using saved HTML samples to test each step.
What Are Google AI Overviews and How Do They Appear in Search?
Google AI Overviews are AI-generated summaries that show up in standard search results when Google sees that it might be helpful to the user. They may contain explanatory text, lists, inline links, and cards that link to other websites. Some also have a Show more option that reveals additional content.
AI Overviews are different from Google AI Mode, which presents a conversational search format that supports follow-up questions. AI Overviews don't appear for every query, and their availability varies by language and location.
This complicates extracting AI Overview data. A single search could yield no overview, or it could yield a long answer with citations in various parts of the answer, some of which might not show up until after the page finishes loading or the user expands the answer. Google's HTML structure may change, which may break previously working selectors.
These summaries, along with links to the sources, enable developers and SEO researchers to follow cited sites, evaluate answers from various regions, and track how answers change over time.

Building the Google AI Overview Scraper Step by Step
We'll develop the scraper gradually, beginning with the Python environment, setting up the browser, and setting up a proxy. We'll then analyze the HTML structure, find the AI Overview text, and retrieve a summary and a link to the citation. We'll use the same Python project and saved HTML samples to test each step before exporting the results to JSON.
Step 1: Set Up Your Python Project
In this guide, we'll be using PyCharm, an integrated development environment (IDE) for Python, on macOS, but you can use the same Python scripts in VS Code, another Python IDE, or in a terminal on Windows/Linux.
You'll need Python 3.10 or newer and three libraries: Playwright for loading and interacting with web pages, BeautifulSoup for parsing the HTML and collecting the data, and python-dotenv to load your proxy credentials from a file.
First, open PyCharm and click New Project, then give the project the name google-ai-overview. Select Project venv as the environment type, click the Python interpreter you want to use, and click Create. It will automatically create a virtual environment to separate the project's dependencies.
For other editors or terminals, create a virtual environment manually as follows:
macOS/Linux:
python3 -m venv .venv
source .venv/bin/activateWindows (PowerShell):
py -m venv .venv
.venv\Scripts\Activate.ps1After preparing your environment, open a terminal (in PyCharm, go to the Terminal tool window) and install the necessary libraries and the Chromium browser:
python -m pip install playwright beautifulsoup4 python-dotenv
python -m playwright install chromiumOn Windows, if PowerShell denies access to Activate.ps1 and tells you that executing scripts is disabled, in the same PowerShell window, type the following command: Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass; then run Activate.ps1 once more. If Chromium on Linux doesn't start due to missing system libraries, use python -m playwright install-deps chromium (may prompt for password).
We're going to write one Python file per step; this way, you can test each part of the scraper separately.
Step 2: Initialize Playwright and Launch the Browser
To get the AI Overviews, we must ensure that Playwright can launch Chromium and render JavaScript. Playwright launches a browser to run the scripts and interact with page elements, unlike a plain HTTP request.
Now make a new Python file called step2_launch_browser.py and paste the following into it:
import os
from pathlib import Path
from playwright.sync_api import expect, sync_playwright
screenshot = Path(__file__).with_name("step2_browser_output.png")
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=False,
executable_path=os.getenv("CHROMIUM_PATH") or None,
)
context = browser.new_context(viewport={"width": 1000, "height": 600})
page = context.new_page()
page.set_content("""
<main style="font: 22px Arial; padding: 48px">
<h1>Playwright browser check</h1>
<p id="status">Waiting for JavaScript...</p>
</main>
<script>
setTimeout(() => {
document.querySelector("#status").textContent =
"JavaScript rendered successfully";
}, 300);
</script>
""")
expect(page.locator("#status")).to_have_text("JavaScript rendered successfully")
page.screenshot(path=str(screenshot))
print("Browser launched and JavaScript executed successfully.")
context.close()
browser.close()The script starts Chromium, initializes an isolated context, and loads a simple test page. The text is displayed in the status message on the page, and Playwright validates that the expected text is present before saving a screenshot.
When headless is set to False, a visible browser window will open. If you are running a machine without a display (such as a Linux server), you need to change it to headless=True. The optional CHROMIUM_PATH setting is only needed when using a separately installed Chromium executable. It can be left unset with the browser installed in Step 1.
Use PyCharm to run step2_launch_browser.py. If the check succeeds, you will have step2_browser_output.png next to your Python file. From a terminal, you can also run python step2_launch_browser.py.

Step 3: Configure Byteful Proxies for Your Scraper
Proxies let you route traffic through a proxy IP address in your preferred location, and when used across different locations, they help you gather search data from your desired location.
Playwright supports proxy configuration at the browser or browser context level, allowing you to specify which requests use them. Suitable proxies would be:
- Residential proxies: These use IP addresses from real home connections, with location targeting, which is what location-specific search results depend on. Pick sticky sessions to keep one exit IP through a capture session, or rotating sessions to spread many queries across different IPs.
- ISP proxies: Also called static residential proxies, these are ISP-assigned IPs hosted on datacenter infrastructure, and they keep the same address across sessions. Choose them when you want to track how an answer changes over time from one consistent IP.
- Datacenter proxies: Hosted in commercial data centers, these are usually the fastest and cheapest option, which suits development and testing. Websites can detect datacenter IP ranges and may limit their traffic, so they are not the right pick for collecting live search results.
For this tutorial, we'll use a Byteful residential proxy with a sticky session. This lets us target a specific location while keeping the same exit IP during the test session.
If you're new to Byteful and want to try residential proxies, you can get 1 GB of free residential data after a quick identity check. Head to our dashboard, click Residential Proxies, and open the Generator tab. Under Format Settings, select Sticky and HTTP, then choose a country under Targeting Settings. Your generated proxy will appear on the right. Click Copy to get the host, port, username, and password.

Note: Byteful proxies block requests sent directly to IP addresses by default, and residential proxies block all IP-based traffic. Nothing in this tutorial is affected, since every request here uses a domain name. Keep this in mind if you adapt the code to fetch a URL by its IP address.
Create a new Python file named step3_verify_byteful_proxy.py and add:
import os
from dotenv import load_dotenv
from playwright.sync_api import sync_playwright
load_dotenv()
proxy = {
"server": os.environ["BYTEFUL_PROXY_SERVER"],
"username": os.environ["BYTEFUL_PROXY_USERNAME"],
"password": os.environ["BYTEFUL_PROXY_PASSWORD"],
}
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=True, executable_path=os.getenv("CHROMIUM_PATH") or None
)
context = browser.new_context(proxy=proxy)
try:
page = context.new_page()
response = page.goto(
"https://ipinfo.io/json",
wait_until="domcontentloaded",
timeout=30000,
)
if response is None or not response.ok:
raise RuntimeError("The IP-check request failed.")
result = response.json()
print(f"Exit IP: {result['ip']}")
print(f"Location: {result.get('city', 'Unknown')}, "
f"{result.get('region', 'Unknown')}, "
f"{result.get('country', 'Unknown')}")
finally:
context.close()
browser.close()Make sure there is a file called .env in the same folder prior to running the script. In PyCharm, select the project folder, right-click, and choose New > File. Fill in your proxy information, using the host and port that you generated:
BYTEFUL_PROXY_SERVER=http://host:port
BYTEFUL_PROXY_USERNAME=your-username
BYTEFUL_PROXY_PASSWORD=your-passwordThe script loads this file when it's executed, and the values in it can be accessed through the os.environ dict, which means the same setup will work in a macOS, Windows, or Linux terminal and PyCharm. Don't share the file, and place .env in your .gitignore file if you are using Git.
Run the file. The script accesses an IP-checking service via the specified proxy and prints its exit IP address and the reported location. Compare the above details with the settings you selected in our dashboard.

The proxy is used by requests within the browser context specified on it. The following steps test extraction using saved HTML samples without making live Google Search requests. Set up the same proxy settings in the browser context that you use to get the search results for authorized live collection.
Note: Comply with Google's relevant access requirements. For large-scale Google Search scraping using datacenter or static residential ISP proxies, we also require prior approval.
Step 4: Identify the AI Overview in Search Results
Not all Google searches show an AI Overview, and some appear after the initial search results load. To get any data, we must first locate the AI Overview section and determine if its content is available.
Begin by looking at a Google Search Results page with an AI Overview. To open Chrome DevTools, right-click the heading of the overview and select Inspect. Search for the heading element and the content around it, and any Show more control.
At the time of writing, the selector div[jsname][role="heading"] matched the AI Overview heading in our inspected live results. Google's markup may vary; compare the selector with the HTML to be worked with, and don't assume it will always match.

To achieve a reproducible first test, we'll use an HTML fixture that is saved with an AI Overview that will show up after a short delay due to JavaScript. This allows us to verify AI Overview detection without relying on Google's ability to create an overview for that query. The sample files are simplified test pages built for this tutorial. They are not copies of real Google results
Create a new file named step4_detect_ai_overview.py and place step4_sample_results.html in the same folder. You can download all the Python scripts and sample HTML files for Steps 2 to 7.
import os
import re
from pathlib import Path
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
folder = Path(__file__).resolve().parent
source = folder / os.getenv("AIO_HTML_FILE", "step4_sample_results.html")
if not source.is_file():
raise FileNotFoundError(f"Save the permitted HTML sample as {source.name}")
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=True,
executable_path=os.getenv("CHROMIUM_PATH") or None,
)
context = browser.new_context(viewport={"width": 1280, "height": 850})
page = context.new_page()
try:
page.set_content(
source.read_text(encoding="utf-8"),
wait_until="domcontentloaded",
)
try:
page.locator("#search").wait_for(
state="attached", timeout=3000
)
except PlaywrightTimeoutError:
status = "page_unrecognized"
else:
heading = page.locator(
'div[jsname][role="heading"]'
).filter(
has_text=re.compile(r"^\s*AI Overview\s*$", re.I)
).first
try:
heading.wait_for(state="visible", timeout=6000)
except PlaywrightTimeoutError:
status = "not_detected"
else:
status = "detected"
show_more = page.locator(
'[aria-label="Show more AI Overview"]'
).first
if show_more.count() and show_more.is_visible():
show_more.click()
print(f"AI Overview status: {status}")
page.screenshot(
path=str(folder / "step4_detection_output.png"),
full_page=True,
)
finally:
context.close()
browser.close()The script loads the saved HTML into the Chromium browser, waits for the search results container, and looks for an AI Overview heading. If it detects any matching Show more control, it will expand the content before taking a screenshot.
It has three outcomes: detected, not_detected (because the heading has not been found within the timeout), and page_unrecognized (because the search container that is expected has not been found). A not_detected result does not indicate that Google failed to include the overview, because changes in selectors or delayed rendering might lead to the same results.

This step indicates if the desired elements exist. We'll extract the summary text and citations in the following steps.
Step 5: Extract the AI Overview Text
Once we can identify an AI Overview, we are now able to extract a summary from it without the citation cards and other search results that are not related to the overview. We'll use BeautifulSoup to extract the relevant paragraphs from the HTML that has been rendered.
Make a new file called step5_extract_overview_text.py. In this case, let's use a different HTML fixture (step5_sample_overview.html) that includes a multi-paragraph AI Overview that has expandable content. The selectors match this test fixture and need to be verified against the actual structure of the page prior to using elsewhere.
import os
import re
from pathlib import Path
from bs4 import BeautifulSoup
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
folder = Path(__file__).resolve().parent
source = folder / "step5_sample_overview.html"
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=True, executable_path=os.getenv("CHROMIUM_PATH") or None
)
page = browser.new_page()
try:
page.set_content(source.read_text(encoding="utf-8"))
heading = page.locator('div[jsname][role="heading"]').filter(
has_text=re.compile(r"^\s*AI Overview\s*$", re.I)
).first
try:
heading.wait_for(state="visible", timeout=5000)
except PlaywrightTimeoutError:
status, summary = "not_detected", ""
else:
panel = heading.locator("xpath=ancestor::section[1]")
show_more = panel.locator('[aria-label="Show more AI Overview"]').first
if show_more.count() and show_more.is_visible():
show_more.click()
soup = BeautifulSoup(page.content(), "html.parser")
label = next(
(tag for tag in soup.select('div[jsname][role="heading"]')
if tag.get_text(" ", strip=True).lower() == "ai overview"),
None,
)
overview = label.find_parent("section") if label else None
if overview is None:
status, summary = "markup_changed", ""
else:
paragraphs = [
tag.get_text(" ", strip=True)
for tag in overview.select(".answer p")
]
summary = "\n\n".join(text for text in paragraphs if text)
status = "success" if summary else "empty_summary"
print(f"Extraction status: {status}")
if summary:
print(f"\nAI Overview text:\n{summary}")
finally:
browser.close()The script expands the overview (if the matching button is there), and BeautifulSoup receives the new HTML. It then only picks up paragraphs within the .answer element of the overview, excluding the source cards in the <aside> element. Other search results, not in the selected portion, are also excluded from the summary.
If there is no heading, the script returns not_detected. If the container for the overview is either absent or does not have any paragraphs that can be extracted from it, it returns the string markup_changed or empty_summary, respectively.
Execute the file in PyCharm and view the extracted text.

Step 6: Extract Source Links and Citations
Google AI Overviews may contain citations in the text and source cards that reference supporting websites. These links need to be extracted without catching URLs from standard Google search results.
Make a new Python file called step6_extract_citations.py. We'll use a separate HTML fixture (step6_sample_citations.html) that contains inline citations, source cards, duplicate URLs, and links with missing information.
import os
import re
from pathlib import Path
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
folder = Path(__file__).resolve().parent
sample = folder / os.getenv("AIO_HTML_FILE", "step6_sample_citations.html")
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=True, executable_path=os.getenv("CHROMIUM_PATH") or None
)
page = browser.new_page()
try:
page.set_content(sample.read_text(encoding="utf-8"))
heading = page.locator('div[jsname][role="heading"]').filter(
has_text=re.compile(r"^\s*AI Overview\s*$", re.I)
).first
try:
heading.wait_for(state="visible", timeout=5000)
except PlaywrightTimeoutError:
status, citations = "not_detected", []
else:
show_more = page.locator('[aria-label="Show more AI Overview"]').first
if show_more.count() and show_more.is_visible():
show_more.click()
soup = BeautifulSoup(page.content(), "html.parser")
label = next(
(tag for tag in soup.select('div[jsname][role="heading"]')
if tag.get_text(" ", strip=True).lower() == "ai overview"),
None,
)
overview = label.find_parent("section") if label else None
citations, seen = [], set()
if overview:
links = overview.select("aside.citations a[href]")
links += overview.select(".answer a[data-citation][href]")
for link in links:
url = link["href"].strip()
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.netloc or url in seen:
continue
title = link.get_text(" ", strip=True) or link.get("aria-label") or parsed.netloc
citations.append({"title": title, "url": url})
seen.add(url)
status = "success" if citations else ("no_citations" if overview else "markup_changed")
print(f"Citation status: {status}")
for number, citation in enumerate(citations, start=1):
print(f"{number}. {citation['title']}: {citation['url']}")
finally:
browser.close()The script first checks for an AI Overview and, if there is an AI Overview and a matching control, it expands it. BeautifulSoup then extracts the links from within the citation cards and answer text in the overview, saving each source as a dictionary with the title and URL.
It handles source cards first, eliminates duplicate URLs, and if a citation title is not provided, it uses the link's aria-label, or the website's domain name if there is no label. Unrecognized URLs (those that don't have an HTTP or HTTPS protocol) are ignored. If no citations are provided, the script outputs no_citations, and if no heading or overview container is found, it outputs not_detected or markup_changed, respectively.
The selectors match our test fixture. For actual Google Search HTML, use DevTools to examine the citation elements and modify them so that they reflect the current structure.

Step 7: Save the Extracted Data as JSON
We can combine extracted AI Overview summaries and citations into a JSON file to be used for further analysis. We'll also note the search query used, the location requested, and the extraction timestamp to see which results originated from which location.
Make a new file called step7_export_ai_overview_json.py in Python. This script combines the detection and extraction logic of the previous steps and employs its own HTML fixture (step7_sample_results.html).
import json
import os
import re
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from playwright.sync_api import sync_playwright
folder = Path(__file__).resolve().parent
source = folder / os.getenv("AIO_HTML_FILE", "step7_sample_results.html")
output = folder / "step7_ai_overview_results.json"
result = {
"query": None,
"requested_location": None,
"verified_location": None,
"captured_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"source": "saved_html",
"source_file": source.name,
"status": "error",
"summary": "",
"citations": [],
}
try:
with sync_playwright() as playwright:
browser = playwright.chromium.launch(
headless=True, executable_path=os.getenv("CHROMIUM_PATH") or None
)
try:
page = browser.new_page()
page.set_content(source.read_text(encoding="utf-8"))
search = page.locator("#search")
if search.count() == 0:
raise ValueError("Search results container was not found")
result["query"] = search.get_attribute("data-query")
result["requested_location"] = search.get_attribute("data-region")
heading = page.locator('div[jsname][role="heading"]').filter(
has_text=re.compile(r"^\s*AI Overview\s*$", re.I)
).first
try:
heading.wait_for(state="visible", timeout=4000)
except PlaywrightTimeoutError:
declared_absent = search.get_attribute("data-overview-state") == "absent"
result["status"] = "no_overview" if declared_absent else "not_detected"
else:
panel = heading.locator("xpath=ancestor::section[1]")
show_more = panel.locator('[aria-label="Show more AI Overview"]').first
if show_more.count() and show_more.is_visible():
show_more.click()
soup = BeautifulSoup(panel.inner_html(), "html.parser")
paragraphs = [p.get_text(" ", strip=True) for p in soup.select(".answer p")]
result["summary"] = "\n\n".join(p for p in paragraphs if p)
seen = set()
links = soup.select("aside.citations a[href]")
links += soup.select(".answer a[data-citation][href]")
for link in links:
url = link["href"].strip()
parsed = urlparse(url)
if parsed.scheme not in ("http", "https") or not parsed.netloc or url in seen:
continue
title = link.get_text(" ", strip=True) or link.get("aria-label") or parsed.netloc
result["citations"].append({"title": title, "url": url})
seen.add(url)
if not result["summary"]:
result["status"] = "empty_summary"
elif not result["citations"]:
result["status"] = "partial"
else:
result["status"] = "success"
finally:
browser.close()
except Exception as exc:
result["status"] = "error"
result["error"] = f"{type(exc).__name__}: {exc}"
output.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
print(f"Extraction status: {result['status']}")
print(f"Summary characters: {len(result['summary'])}")
print(f"Unique citations: {len(result['citations'])}")
print(f"Saved: {output.name}")The script is designed to extract the summary and the unique links for the citations and save them with the query and location metadata. It uses success for complete results, partial for partial results when citations are missing, and empty_summary in the absence of any summary text. It also differentiates between the test fixture having no overview (no_overview) and an unmatched heading (not_detected), and records unexpected errors.
The requested location is provided by the saved HTML's metadata. Since this is a local file, verified_location is left empty, not to imply that a proxy location was verified.
Execute the script in PyCharm and view the saved information in step7_ai_overview_results.json.

How to Verify Your Google AI Overview Scraper Works
The script may have no errors but may not be able to produce accurate data. Beware before using the results of the summary, citations, and extraction status. They should be checked for accuracy against the original HTML.
Open step7_export_ai_overview_json.py in PyCharm, and run it on the sample HTML files. To choose a fixture, go to Run > Edit Configurations and add an AIO_HTML_FILE environment variable set to the fixture filename. step7_ai_overview_results.json is overwritten with every run, so be sure to check the file after each run.
Instead, from a terminal, set the variable for each run:
macOS/Linux:
AIO_HTML_FILE=step7_no_overview.html python step7_export_ai_overview_json.pyWindows (PowerShell):
$env:AIO_HTML_FILE='step7_no_overview.html'
python step7_export_ai_overview_json.py
Remove-Item Env:AIO_HTML_FILEIn PowerShell, the variable remains until it is removed. Steps 4 and 6 also reference AIO_HTML_FILE, so if you run them again, remove the AIO_HTML_FILE before doing so.
Here's what to check:
- Successful extraction: Use step7_sample_results.html to test and compare the summary to the original HTML. Ensure that all three paragraphs are present and that the two unique citation URLs match their source links.
- Missing AI Overview: Check for no_overview with step7_no_overview.html. This fixture contains a specific indication that the overview is absent, so that the script can distinguish this from a detection failure.
- Incomplete extraction: Test with step7_no_citations.html. The script should report "partial" instead of "success", as the summary is present but citations are missing.
- Unexpected HTML: Test with step7_unrecognized_results.html to make sure that an unrecognized page results in an error, not a blank successful result.
If the status is not_detected for live HTML, this may be because of outdated selectors, or because the HTML has not yet been rendered. Always look at the page before dismissing the possibility that Google wasn't showing the overview.
If you are using our proxies, execute the IP verification from Step 3 individually and verify that the exit IP and the reported location are the same as you set up on the proxy. The stored HTML tests don't send requests through a proxy.

Why Your AI Overview Scraper Isn't Working (and How to Fix It)
Your scraper can report no errors, and you may even be getting data back, but it could still be returning empty summaries or even data that is wrong. First, check the extraction status in your JSON file, and then look at the HTML to see where it went wrong.
Several challenges can impact the results of AI Overview extraction:
| Problem | Likely cause and fix |
|---|---|
| AI Overview isn't detected | Check whether the source HTML contains an overview. If the script returns not_detected, inspect the heading selector and confirm the content has finished loading. |
| Summary text is empty | The .answer p selector may no longer match the summary paragraphs. Inspect the overview container in DevTools and update the selector to match the current HTML. |
| Only part of the answer is extracted | Some content may remain collapsed behind Show more. Confirm the script expands the relevant section before passing the rendered HTML to BeautifulSoup. |
| Citation links are missing | Check whether the source links appear inside citation cards or inline elements. Update the link selectors and verify that their href attributes contain valid URLs. |
| Previously working selectors fail | Google may have changed its HTML structure. Compare the current elements with your original sample and update the affected selectors rather than modifying the entire script. |
| Byteful proxy connection fails | Check the proxy endpoint, port, protocol, and authentication credentials. An HTTP 407 response indicates a proxy authentication problem. In Playwright, rejected proxy credentials can also appear as a Timeout 30000ms exceeded error from page.goto instead of a 407. |
| Results show the wrong location | Verify the exit IP using the IP-checking service from Step 3. Confirm the region selected in our dashboard and check the browser's language settings, which can also influence localized results. |
The reliability of a no_overview status depends on the source in fact stating that there is no overview; our test fixture explicitly marks this. In the case of live pages, further inspection is needed before not_detected can be considered a missing AI Overview.


