DEV Community

coreclaw
coreclaw

Posted on

Google Autocomplete Scraper: How to Build a Keyword Research Pipeline with Python

Google Autocomplete Scraper: How to Build a Keyword Research Pipeline with Python

A Google Autocomplete scraper collects the suggestion phrases Google displays as you type a query, and it is the fastest way to build a keyword research dataset from real search behavior rather than from estimates. The workflow is straightforward: feed a list of seed keywords, expand each seed with modifier letters and question words to trigger the suggestion engine, deduplicate the returned phrases, cluster them by topic, and export a CSV your content or PPC team can act on. This guide is for SEO specialists, content strategists, and developers who want a repeatable Python pipeline for keyword expansion — not another round of typing queries into a browser by hand.

TL;DR

  • Autocomplete suggestions are real queries typed by real searchers, surfaced by Google itself — they reveal demand and phrasing that volume tools often miss, especially for long-tail and emerging topics.
  • Manual autocomplete research does not scale: suggestions depend on the exact prefix typed, the locale, and the device, so capturing them one search at a time produces inconsistent, unpersisted data.
  • The Python script below reads search records (from a file or a managed scraping endpoint configured via environment variables), expands seeds with a modifier matrix, deduplicates and clusters the suggestions, and writes a prioritized CSV.
  • Collect only public search results, keep request volumes reasonable, and follow your data provider's terms and applicable law.

Why Manual Autocomplete Research Breaks Down

The traditional workflow looks like this: type a seed keyword, note the suggestions, type the seed plus "a", then "b", then "how", then "why" — and write everything into a spreadsheet. For one topic, that is an hour of clicking. For a site targeting hundreds of keywords across multiple markets, it never gets finished, and the data quality is worse than it looks:

  • Prefix dependence. Suggestions are generated for the exact character sequence typed. Missing one modifier letter means missing the suggestion set that letter triggers.
  • Locale and language variance. The same seed produces entirely different suggestions in different countries, languages, and even between google.com and a country domain. Manual checks on one browser reflect only one configuration.
  • No persistence. Copy-pasting suggestions into a doc gives you no timestamps, no provenance, and no way to diff this month's suggestions against last month's.
  • Drift. Autocomplete reflects recent search behavior. Trending queries appear and disappear; a list captured in January can be stale by March.
  • Scale. A serious expansion run — 50 seeds × 26 letter modifiers × 8 question prefixes — is over a thousand queries. Nobody does that manually, which is exactly why most keyword lists are shallow.

A script-based pipeline fixes all of this: it produces timestamped, machine-readable records you can deduplicate, cluster, diff between runs, and feed straight into an editorial calendar or ad group structure.

What an Autocomplete Extraction Workflow Returns

For each (seed, modifier) pair, the record you care about looks like this:

Field Why it matters
seed_keyword The base query that was expanded; lets you trace every suggestion back to its source cluster.
modifier The prefix appended to the seed ("a", "how", "best"...); shows which expansion path surfaced the phrase.
suggestions The list of autocomplete phrases returned for that prefix.
locale The language and country configuration used; required for multi-market research.
collected_at Timestamp so you can track how the suggestion set shifts over time.

The exact field names depend on where your data comes from. The workflow below normalizes a few common variants, so it works whether your records come from an in-house collector or a managed scraping API — as long as the output is structured JSON.

A Runnable Python Keyword Expansion Pipeline

The script reads autocomplete records from a JSONL file, or fetches them from a managed endpoint when you configure one through environment variables. It expands each seed with a modifier matrix, deduplicates phrases across seeds, clusters them with a root-phrase heuristic, and writes a CSV sorted by how many expansion paths surfaced each phrase — a useful proxy for how central a phrase is to the topic.

import csv
import json
import os
import re
from collections import defaultdict
from datetime import datetime, timezone

# --- Configuration (always via environment variables, never hard-coded) ---
CORECLAW_API_KEY = os.environ.get("CORECLAW_API_KEY", "")
CORECLAW_WORKER_ENDPOINT = os.environ.get("CORECLAW_WORKER_ENDPOINT", "")
INPUT_FILE = os.environ.get("AUTO_INPUT_FILE", "autocomplete_records.jsonl")
OUTPUT_FILE = os.environ.get("AUTO_OUTPUT_FILE", "keyword_expansion.csv")

LETTER_MODIFIERS = [chr(c) for c in range(ord("a"), ord("z") + 1)]
QUESTION_MODIFIERS = ["how", "what", "why", "when", "where", "which", "who", "is", "can", "best"]

STOPWORDS = {
    "the", "a", "an", "for", "to", "of", "in", "on", "and", "with",
    "how", "what", "why", "when", "where", "which", "who", "is", "can", "best",
}


def load_records(path: str) -> list:
    records = []
    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                records.append(json.loads(line))
    return records


def expansion_plan(seeds: list) -> list:
    """Return every (seed, modifier) pair that should be queried."""
    pairs = []
    for seed in seeds:
        for mod in QUESTION_MODIFIERS:
            pairs.append((seed, f"{seed} {mod}"))
        for letter in LETTER_MODIFIERS:
            pairs.append((seed, f"{seed} {letter}"))
    return pairs


def extract_suggestions(record: dict) -> list:
    """Pull suggestion phrases out of a record, tolerating schema variants."""
    raw = record.get("suggestions") or record.get("autocomplete") or []
    phrases = []
    for item in raw:
        if isinstance(item, str):
            phrases.append(item)
        elif isinstance(item, dict):
            phrase = item.get("suggestion") or item.get("phrase") or item.get("query") or ""
            if phrase:
                phrases.append(phrase)
    return phrases


def root_phrase(query: str) -> str:
    """A light clustering key: first two meaningful words, lowercase."""
    words = re.findall(r"[a-z0-9']+", query.lower())
    core = [w for w in words if w not in STOPWORDS]
    return " ".join(core[:2]) if core else query.lower()


def main() -> None:
    records = load_records(INPUT_FILE)
    if not records:
        raise SystemExit(f"No records found in {INPUT_FILE}")

    phrase_map = defaultdict(lambda: {"text": "", "sources": set(), "modifiers": set()})

    for record in records:
        seed = record.get("seed_keyword") or record.get("query") or ""
        modifier = record.get("modifier") or ""
        for phrase in extract_suggestions(record):
            key = phrase.strip().lower()
            entry = phrase_map[key]
            entry["text"] = phrase.strip()
            entry["sources"].add(seed)
            entry["modifiers"].add(modifier)

    rows = []
    for key, entry in phrase_map.items():
        rows.append({
            "keyword": entry["text"],
            "root_phrase": root_phrase(entry["text"]),
            "source_count": len(entry["sources"]),
            "seed_keywords": "; ".join(sorted(s for s in entry["sources"] if s)),
            "expansion_paths": "; ".join(sorted(m for m in entry["modifiers"] if m)),
        })

    # Phrases surfaced by more expansion paths are likely broader topical anchors.
    rows.sort(key=lambda r: (-r["source_count"], r["keyword"]))

    fieldnames = ["keyword", "root_phrase", "source_count", "seed_keywords", "expansion_paths"]
    with open(OUTPUT_FILE, "w", newline="", encoding="utf-8") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerows(rows)

    print(f"Records processed: {len(records)}")
    print(f"Unique keyword phrases: {len(rows)}")
    print(f"Output written to: {OUTPUT_FILE}")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Two notes on the design:

  • The expansion_plan function is also your collection checklist: it defines the exact (seed, modifier) pairs your collector should query. A managed source that accepts the expanded prefix as the query makes the collection step trivial — with the CoreClaw Google Search Scraper, you configure collection through environment variables, keep the endpoint URL and credentials out of source control, and pipe the structured results straight into this script.
  • If you want the script to fetch records itself rather than reading a file, set CORECLAW_WORKER_ENDPOINT and CORECLAW_API_KEY in your environment and replace load_records with an authenticated request to your verified endpoint. The same script then runs unchanged on your laptop, in CI, and on a scheduler.

Representative Output

A few rows from a run over two seeds (cold brew coffee, espresso machine) look like this:

keyword,root_phrase,source_count,seed_keywords,expansion_paths
cold brew coffee ratio,cold brew,2,cold brew coffee; espresso machine,cold brew coffee b; cold brew coffee how
best espresso machine for home,best espresso,1,espresso machine,espresso machine best; espresso machine e
cold brew coffee concentrate,cold brew,1,cold brew coffee,cold brew coffee c
how long does cold brew last,cold brew,1,cold brew coffee,cold brew coffee how
Enter fullscreen mode Exit fullscreen mode

Read the output like a strategist, not a raw list:

  • source_count 2+ — the phrase sits between two of your clusters. Treat it as a pillar-page candidate or a category bridge.
  • expansion_paths showing multiple letters — the phrase is robust across prefixes, a sign of stable demand rather than a one-off trending query.
  • Question-modifier phrases ("how long does cold brew last") — direct FAQ, product page, or documentation content candidates.
  • Single-source single-path phrases — long-tail candidates for supporting posts or ad keywords with low competition.

Keyword Expansion Checklist

Before phrases from the CSV go into your calendar or ad groups:

  • [ ] Deduplicate phrases that differ only in punctuation, spacing, or word order.
  • [ ] Filter out phrases containing competitor brand names unless you have a strategy for comparison content.
  • [ ] Check intent per cluster: "best X" and "X vs Y" phrases belong on comparison pages, not blog posts.
  • [ ] Pin one locale per dataset; never mix suggestions captured under different countries or languages.
  • [ ] Re-run the expansion monthly and diff the phrase sets to catch emerging queries early.
  • [ ] Map every retained phrase to one owner page or ad group with a canonical target.
  • [ ] Record the collection date so stale data never quietly drives decisions.

Build vs Buy: Sourcing the Autocomplete Data

Approach Best for Maintenance burden Notes
Manual capture Spot-checking a handful of seeds Low Prefix-dependent, no history, does not scale
Self-hosted collection Engineering teams with proxy and parsing experience High Suggestion behavior and markup shift; expect constant repair
Managed search data API Content, SEO, and growth teams needing scheduled structured data Low Structured JSON, schedulable, no proxy management

Self-hosted autocomplete collection means handling unbuffered streaming responses, locale parameters, and rate behavior for every market you target. Most teams get more value from spending that engineering time on the keyword strategy itself. If you go the managed route, the CoreClaw Store lists ready-made workers for Google Search, Google Maps, e-commerce, and social platforms — and if your target structure is not covered, you can build a custom worker through the CoreClaw worker console.

Business Use Cases

Content strategists turn high source_count phrases into pillar topics and question phrases into FAQ sections. One expansion run over a site's core clusters typically yields several hundred actionable phrases — enough for two quarters of editorial planning.

PPC and paid social teams use the phrase set to build tightly themed ad groups. Autocomplete phrasing mirrors how people actually search, which improves ad relevance scores compared with brainstormed keyword lists.

E-commerce teams expand category seeds ("air fryer", "running shoes") to surface modifier demand — sizes, materials, use cases — and fold the phrases into category page copy, filters, and product descriptions.

SEO agencies use expansion runs in client audits: showing a client that Google surfaces 40+ distinct demand phrases around their core service, of which their site targets five, makes the content gap concrete.

AI and RAG builders use the phrase set as evaluation queries: if your retrieval pipeline returns good answers for the top expanded phrases in your domain, it covers how users actually ask.

Limitations and Compliance

  • Public data only. Autocomplete suggestions are what Google publicly displays to every user typing a query. Do not attempt to access private accounts, restricted interfaces, or non-public data.
  • Respect platform terms. Google has terms of service and technical protections around automated access. Keep request volumes reasonable, review the current terms before deploying, and prefer a provider that handles compliance-sensitive collection for you.
  • No CAPTCHA evasion. If a challenge appears, stop and reduce frequency or switch to an officially supported or managed data source. Do not build bypass logic.
  • No credential abuse. Never use stolen credentials or fake accounts to reach data.
  • Locale discipline. Suggestions vary by country, language, and device. Pin your collection configuration per dataset so comparisons stay meaningful, and label every record with its locale.
  • Snapshot, not truth. An autocomplete set is a snapshot of recent search behavior on a given day. Refresh it on a schedule, date-stamp every record, and re-diff before major content decisions. Suggestions also contain no search volume — pair them with a volume tool for prioritization.

FAQ

Is autocomplete data the same as keyword search volume?
No. Autocomplete shows phrases searchers type, which proves the phrasing exists and is currently active — but it carries no volume estimate. Use the phrase set to define your target list, then pull volume figures from a dedicated tool to prioritize.

Do suggestions differ between desktop and mobile?
Yes, they can. If mobile matters to your business, collect and store mobile-locale datasets separately instead of assuming one set covers both.

How many seeds should one expansion run include?
Enough to cover your site's main topic clusters — typically 20-100 seeds. The modifier matrix multiplies quickly (one seed means 36 prefixes in this script), so start with your highest-value clusters and expand coverage over successive runs.

Can I run this for languages other than English?
Yes, if your data source supports the locale. The root_phrase clustering heuristic assumes space-separated words, so adjust it for languages with different morphology.

How often should I refresh autocomplete data?
Monthly is a sensible default. Weekly refreshes make sense for seasonal or trend-sensitive niches where new queries appear fast; the diff between runs is where the value is.

Does this replace traditional keyword tools?
No — it complements them. Autocomplete gives you real phrasing and emerging queries; volume tools give you demand estimates and difficulty scores. The strongest keyword research uses both.

Is collecting Google autocomplete data legal?
Laws vary by jurisdiction, and collecting publicly visible suggestion data is generally treated as permissible in many regions — but you must comply with Google's terms of service, local privacy laws, and your provider's terms. This guide is not legal advice.

Next Steps

Pick ten seed keywords that map to your site's core topic clusters, generate the expansion plan, collect suggestion records for every (seed, modifier) pair, and run the script above. You should end up with a CSV of unique phrases ranked by how many expansion paths surfaced them — reviewed with a strategist's eye, that list is your next content cycle's keyword plan, built from real search behavior in about an hour.

If you need structured Google search data at scale without maintaining proxies or parsers, start with the CoreClaw Google Search Scraper, or browse the CoreClaw Store for ready-made workers across search, maps, e-commerce, and social platforms.

Top comments (0)