
Solar System Position Tracker
November 20, 2025
Is it a prime number?
January 9, 2026The Case of the "Ghost" Data: Engineering a Robust AI Reputation Scraper
Tags: Python, SerpApi, OpenAI, Data Engineering, Debugging
As developers, we often assume that if an API returns a 200 OK status, our job is done. But recently, while building a competitive intelligence tool to track how AI models (like ChatGPT and Google’s AI Overviews) perceive a major national brand, I ran into a "silent failure" that taught me valuable lessons about modern search APIs, data hygiene, and the importance of reading the fine print in JSON payloads.
Here is the story of how we debugged a scraper that was "working" perfectly—but returning zero data.
The Objective
The goal was simple: Build a longitudinal scraper to query ChatGPT and Google Search (AI Overviews) for specific brand reputation prompts. The output needed to be:
-
Ecologically Valid: Mimicking a real user on a Desktop in a specific US region.
-
Stateless & Objective: Architected for single-transaction conversations, ensuring that every query starts with a blank slate to prevent context bias from previous turns.
-
Analysis-Ready: Formatted strictly for MAXQDA (qualitative data analysis software), which meant no Markdown (
**bold**), no broken CSV rows, and URLs separated into their own column.
The Problem: The "Silent Failure"
We built the initial scraper using Python and SerpApi. The logs looked great:
[INFO] Querying SerpApi for: 'What does [Brand] do?' [INFO] Found 'ai_overview' key. [INFO] Data saved to csv.
But when we opened the CSV, the response_text column was empty. Every single row. The API was telling us it found an AI Overview, but it wasn't giving us the text.
The Investigation
We built a "diagnostic mode" script to dump the raw JSON response from Google. That’s when we found the smoking gun.
Instead of a standard snippet or text field, Google was returning a "Heavy" AI Overview. Because the answer was too complex to fit in the standard JSON packet, the API gave us a page_token instead of the text.
"ai_overview": {
"page_token": "3KmwqnicxZTNcuI4EMfP..."
}
Essentially, Google was saying: "I have the answer. Here is a ticket to go get it."
The "Gotcha": The Cache Trap
We quickly wrote logic to "redeem" this ticket by making a second API call. But then we hit Error #2: "Google hasn't returned any results for this query."
The Cause: SerpApi (and Google) cache search results. Our script was hitting a cached search from 10 minutes ago. The page_token inside that cache was "stale"—it had expired. When we tried to redeem an expired token, Google rejected it.
The Solution
To fix this, we had to engineer a Two-Step Fetching Logic with strict context enforcement.
1. Force Freshness
We added no_cache: "true" to the initial search parameters. This forces Google to generate a fresh page_token instantly.
2. Context Consistency
We learned that you cannot generate a token in one context (e.g., "Chicago Desktop") and redeem it in another (e.g., "Generic Server"). The second "Expanded" API call must carry the exact same geolocation and device parameters as the first one.
3. recursive Parsing
The "Expanded" JSON result had a completely different structure than the standard result. Instead of a simple string, it returned a list of text_blocks. We wrote a custom parser to stitch these blocks back into a coherent paragraph.
The Code
Here is the core logic that solved the problem (simplified for readability):
# The "Two-Step" Fetch Logic
if "ai_overview" in results:
ai_blob = results.get("ai_overview")
# Step 1: Check for hidden content
if "page_token" in ai_blob:
print("Content hidden behind token. Fetching...")
# Step 2: The Second Call (Must match context!)
token_params = {
"engine": "google_ai_overview",
"page_token": ai_blob["page_token"],
"location": params["location"], # Critical
"gl": params["gl"], # Critical
"device": params["device"] # Critical
}
expanded_data = client.search(token_params).as_dict()
# Step 3: Parse the "Expanded" Structure
if "text_blocks" in expanded_data.get("ai_overview", {}):
# Stitch paragraphs together
blocks = expanded_data["ai_overview"]["text_blocks"]
full_text = "n".join([b.get("snippet", "") for b in blocks])
Data Hygiene: Preparing for Analysis
Getting the text was only half the battle. The Insights team needed the data to be clean for coding. We wrote a middleware function to sanitize the AI output before saving:
-
Markdown Stripper:
re.sub(r'**(.*?)**', r'1', text)removes the bolding that confuses analysis software. -
Citation Extraction: We used regex to pull URLs (
https://...) out of the text body and move them into a separatecitationscolumn, keeping the word counts accurate. -
Safety Encoding: We forced
utf-8-sigencoding to ensure that any emojis or mathematical symbols generated by the AI wouldn't break the CSV file when opened in Excel.
Key Takeaways
-
Don't Trust Status 200: Just because an API call succeeds doesn't mean you got the data. Always validate specific fields.
-
Tokens Expire: If your workflow involves "redeeming" a token (like a
page_tokenornext_pagecursor), you must ensure you are working with live, non-cached data. -
Context is King: In modern AI search, the answer changes based on who (and where) you are. Hardcoding your location parameters (
gl,hl,location) is mandatory for consistent results.
*** This project was a great reminder that scraping AI is not just about grabbing text—it's about understanding the complex, dynamic systems that generate it.



