Sub topic 12
Collecting suggestions with a short script
This chapter shows how to collect autocomplete suggestions with a short Python script. It assumes you can read basic Python, have the requests library installed (pip install requests), and know how to expand a seed by hand with modifiers, question words, and letters. You should also know why autocomplete shows what people type and not how often they type it.
A script does not find better ideas than a manual session. It runs the same expansions faster and records every result in the same format. If you don't plan to run more than a handful of seeds, typing the queries by hand is fine.
What the script does
The script sends one short request per query. Each response is a small list of suggestions, which you clean, deduplicate, and save.
Saving even after a failure matters. If the run stops at query 20 of 40, you keep the 20 results you already have.
Fetching suggestions for one query
Google's suggestion endpoint is unofficial and undocumented. Treat it as something that can change or disappear without notice.
import requests
SUGGEST_URL = "https://suggestqueries.google.com/complete/search"
def suggest(query, language="en"):
response = requests.get(
SUGGEST_URL,
params={"client": "firefox", "q": query, "hl": language},
timeout=10,
)
response.raise_for_status()
# The response is JSON shaped like [query, [suggestion, ...]].
return response.json()[1]
print(suggest("how to brew coffee"))Points to note:
client=firefoxmakes the endpoint return plain JSON. Other client values return different formats, such as JSONP-style wrappers, thatresponse.json()cannot parse.hlsets the interface language. It is a hint, not a guarantee, and the suggestions can still reflect the location of your IP address.timeout=10stops the script from hanging if the server never answers. Without a timeout,requestscan wait indefinitely.raise_for_status()turns HTTP errors such as 429 (too many requests) into exceptions. Without it, an error page would reachresponse.json()and fail with a confusing parse error.- The second item in the list,
[1], holds the suggestions. The first item echoes your query.
Your results come from your own location and settings, so they may differ from someone else's. Run the same query from a different network and you can get a different list.
Expanding a seed with letters
Alphabet expansion appends each letter to the seed and collects what comes back. The function takes the fetching function as an argument. That lets you swap in a cached or fake fetcher while testing, without sending real requests.
import string
import time
def expand_with_letters(seed, fetch):
ideas = set()
for letter in string.ascii_lowercase:
for suggestion in fetch(f"{seed} {letter}"):
ideas.add(suggestion.lower().strip())
time.sleep(1) # pause between requests
ideas.discard(seed.lower())
return sorted(ideas)
# Example: expand_with_letters("cold brew", suggest)Why each line is there:
- A
setremoves duplicates. Neighboring letters often return the same suggestion, such ascold brew coffeefor bothcandco-style completions. lower().strip()normalizes case and whitespace soCold Brewandcold brewcount as one idea.time.sleep(1)limits you to roughly one request per second. Twenty-six letters take about half a minute, which is slow enough to be unremarkable.ideas.discard(seed.lower())removes the bare seed, which is not a new idea.discarddoes not raise an error if the seed is absent, whichremovewould.
Building question and modifier queries
You can also build the question-style and modifier-style queries from your manual workflow and pass them through the same fetcher.
QUESTION_WORDS = ["what", "why", "how", "when", "can", "is"]
MODIFIERS = ["for", "vs", "without", "near me"]
def build_queries(seed):
queries = [f"{word} {seed}" for word in QUESTION_WORDS]
queries += [f"{seed} {modifier}" for modifier in MODIFIERS]
return queries
print(build_queries("cold brew"))Question words go before the seed (how cold brew) and modifiers after it (cold brew vs). Autocomplete matches from the left of the typed text, so position changes which suggestions appear. A query such as how cold brew is incomplete English, but it often prompts a suggestion like how cold brew is made.
Making the run safe: retries, a stop rule, and saved output
The three snippets above work, but a real run needs to handle failures. This version retries a failed request a few times with a growing wait, then stops. It writes results to a CSV file that you can open in your spreadsheet.
import csv
import string
import time
import requests
SUGGEST_URL = "https://suggestqueries.google.com/complete/search"
def suggest(query, language="en"):
response = requests.get(
SUGGEST_URL,
params={"client": "firefox", "q": query, "hl": language},
timeout=10,
)
response.raise_for_status()
return response.json()[1]
def suggest_with_retry(query, attempts=3):
for attempt in range(attempts):
try:
return suggest(query)
except (requests.RequestException, ValueError):
if attempt == attempts - 1:
raise
time.sleep(5 * 2 ** attempt) # wait 5 s, then 10 s
def collect(seed):
queries = [f"{seed} {letter}" for letter in string.ascii_lowercase]
rows = []
try:
for query in queries:
for suggestion in suggest_with_retry(query):
rows.append((seed, query, suggestion.lower().strip()))
time.sleep(1)
except (requests.RequestException, ValueError) as error:
print(f"Stopped early: {error}")
return rows
def save(rows, path):
seen = set()
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.writer(handle)
writer.writerow(["seed", "query", "suggestion"])
for seed, query, suggestion in rows:
if suggestion not in seen and suggestion != seed.lower():
seen.add(suggestion)
writer.writerow([seed, query, suggestion])
if __name__ == "__main__":
save(collect("cold brew"), "cold_brew_suggestions.csv")The CSV keeps the query that produced each suggestion. That column is useful later: when you classify intent, you can see whether an idea came from a question word, a modifier, or a letter.
The ValueError in the except clauses catches a failed JSON parse. requests raises a subclass of ValueError when the body is not JSON, which happens when you get a block page in place of suggestions.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `JSONDecodeError` | The server returned an HTML page or a different format, for example after you were blocked or with a wrong `client` value | Print `response.text[:200]` to see what came back. Use `client=firefox` and slow down |
| `HTTPError: 429` | Too many requests in a short time | Stop, wait, and run later with longer pauses. Do not loop faster |
| Empty list for a query | No suggestions exist for that text | Treat it as a valid result, not an error |
| Odd characters such as `café` | The text was decoded with the wrong encoding | Use `response.json()`, and open the CSV with UTF-8 |
| Different results from your browser | Personalization, location, or language differ between the script and your session | Compare from the same network and `hl` value |
| Script hangs | No timeout set | Always pass `timeout` |
Limits you must keep in mind
- No volume. The script collects ideas, not search counts. The order of suggestions is not a ranking you can rely on. Validation still needs the results page and a separate volume source.
- Unofficial endpoint. Google may change the format, restrict access, or remove it. Do not build a business process that depends on it, and do not assume the behavior is stable between runs.
- Terms of use. Automated access to Google services is covered by Google's terms. Read them before running anything beyond light, occasional use. If you need large volumes, use a source that offers an official, licensed interface.
- Keep the rate low. Roughly one request per second is a ceiling for small jobs. Do not run parallel requests, and do not repeat the same query without caching the answer.
- Do not script the People also ask box. Those questions appear inside the results page and are produced by loading and interacting with it. Scraping results pages is a different and more restricted activity than calling a suggestion endpoint. Collect PAA questions by hand, as in the earlier chapters.
Checking your output
After a run, open the CSV and check three things before you use it:
- The row count is plausible. A 26-letter run that returns 3 rows probably hit a failure and stopped early.
- Suggestions that start with your seed dominate. If they don't, the endpoint may be interpreting your query differently, for example because of the language setting.
- No row is a duplicate or the bare seed.
Then continue with the workflow from the earlier chapters. Sort the ideas by intent, check the most promising ones against the live results page, and bring in volume data from a separate source.
Exercise
Your script prints "Stopped early: Expecting value: line 1 column 1 (char 0)" after about ten queries. Name two likely causes and what you would change before running it again.
Show answer
The error means the response body was not valid JSON, probably because the server returned an HTML or empty page after you sent too many requests, or because the request used a client value that returns a different format. Print the first 200 characters of response.text to see what came back. Then increase the pause between requests, keep client=firefox, cache responses already collected, and wait before retrying so you do not extend a block.
Exercise
Extend build_queries so that it also returns a query for each letter of the alphabet appended to the seed, then explain why the script's final CSV should keep the query column.
Show answer
Add queries += [f"{seed} {letter}" for letter in string.ascii_lowercase] after the modifier line, and add import string at the top. Keeping the query column records how each idea was found (question word, modifier, or letter), so later you can tell which expansion method produced useful ideas and check an odd suggestion against the exact text that triggered it.