This page shows how to fetch Google autocomplete (Google Suggest) suggestions for a search term from Python. The embedded script above is written for Python 2 and fails on Python 3. Below it you'll find a corrected Python 3 version, a JSON variant that needs no XML parser, details on the request parameters, and fixes for the errors people usually run into.
What the example above does
Google's search box calls an autocomplete endpoint as you type. The script above calls that endpoint directly. It sends the query to http://www.google.com/complete/search with output=toolbar, which returns a small XML document. It then reads the data attribute of every <suggestion> element and prints one suggestion per line.
The XML response has roughly this shape:
<?xml version="1.0"?>
<toplevel>
<CompleteSuggestion><suggestion data="devops engineer"/></CompleteSuggestion>
<CompleteSuggestion><suggestion data="devops tools"/></CompleteSuggestion>
</toplevel>Code language: HTML, XML (xml)
Note: Google doesn't publish or support this endpoint as a public API. It has no documentation, no API key and no guaranteed format, and Google can change or restrict it at any time. Use it for small experiments and keyword research, not as a dependency of production systems.
Problems in the original script
unicode(args.query, sys.stdout.encoding)only works in Python 2. Python 3 raisesNameError: name 'unicode' is not defined. In Python 3, command-line arguments are alreadystr, so you don't need to convert them.nargs='?'makes the query optional. If you run the script without an argument,args.queryisNoneand the script crashes instead of printing a usage message.hl='ja'is hard-coded, so suggestions are always requested in Japanese.- It uses plain
http://instead ofhttps://. etree.XML(r.text)passes a decoded string to lxml. If the response includes an XML encoding declaration, lxml raisesValueError: Unicode strings with encoding declaration are not supported. Passing the raw bytes (r.content) avoids this.- There's no timeout and no HTTP status check. A hung connection blocks the script forever, and an error page fails later with a confusing parser error.
pprintis imported but never used.
Prerequisites
- Python 3 (any currently supported release).
- The
requestslibrary. Installlxmlonly if you use the XML variant. - Outbound HTTPS access to Google from the machine running the script.
python3 -m venv venv
source venv/bin/activate
pip install requests lxml
Corrected Python 3 version using the JSON endpoint
The JSON variant uses suggestqueries.google.com with client=firefox and doesn't need lxml. The response is a JSON array. The first element echoes the query, and the second is the list of suggestions, for example ["devops", ["devops", "devops engineer", "devops tools"]].
#!/usr/bin/env python3
"""Print Google autocomplete suggestions for a query."""
import argparse
import json
import sys
import requests
SUGGEST_URL = "https://suggestqueries.google.com/complete/search"
def get_suggestions(query, lang="en", country=None, timeout=10):
params = {
"client": "firefox", # selects the simple JSON response format
"q": query,
"hl": lang, # interface language, e.g. en, ja, de
"ie": "utf-8", # input encoding
"oe": "utf-8", # output encoding
}
if country:
params["gl"] = country # country bias, e.g. us, in, jp
headers = {"User-Agent": "Mozilla/5.0 (suggest-example)"}
resp = requests.get(SUGGEST_URL, params=params, headers=headers, timeout=timeout)
resp.raise_for_status()
# Decode explicitly as UTF-8 (we requested oe=utf-8) to avoid mojibake
data = json.loads(resp.content.decode("utf-8"))
return data[1] if len(data) > 1 else []
def main():
parser = argparse.ArgumentParser(description="Google autocomplete suggestions")
parser.add_argument("query", help="search text to complete")
parser.add_argument("--lang", default="en", help="language code (default: en)")
parser.add_argument("--country", help="optional country code, e.g. us or in")
args = parser.parse_args()
try:
suggestions = get_suggestions(args.query, args.lang, args.country)
except (requests.RequestException, ValueError) as exc:
sys.exit(f"Failed to fetch suggestions: {exc}")
for s in suggestions:
print(s)
if __name__ == "__main__":
main()Code language: PHP (php)
Run it with a query. Put multi-word queries in quotes:
python3 google_suggest.py "devops"
python3 google_suggest.py "kubernetes" --lang en --country in
python3 google_suggest.py "ใใใซใผ" --lang jaCode language: JavaScript (javascript)
You get one suggestion per line. The output looks similar to the lines below, but the exact list changes over time and depends on language, country and Google's own ranking:
devops
devops engineer
devops tools
devops roadmap
devops engineer salary
Corrected XML variant (closest to the original)
If you want to keep the output=toolbar XML format from the example above, here is the corrected parsing code. It uses HTTPS, sets a timeout, checks the status, and passes bytes to lxml so encoding declarations don't cause problems.
#!/usr/bin/env python3
import argparse
import requests
from lxml import etree
def main():
parser = argparse.ArgumentParser()
parser.add_argument("query", help="query string")
parser.add_argument("--lang", default="en")
args = parser.parse_args()
r = requests.get(
"https://www.google.com/complete/search",
params={"q": args.query, "hl": args.lang, "ie": "utf-8",
"oe": "utf-8", "output": "toolbar"},
timeout=10,
)
r.raise_for_status()
root = etree.fromstring(r.content) # bytes, not r.text
for s in root.iter("suggestion"):
print(s.get("data"))
if __name__ == "__main__":
main()Code language: PHP (php)
Request parameters explained
| Parameter | Purpose | Example |
|---|---|---|
q | The partial search text to complete | devops |
client | Chooses the response format on suggestqueries.google.com. firefox returns a plain JSON array | firefox |
output | Chooses the response format on www.google.com/complete/search. toolbar returns XML | toolbar |
hl | Language of the suggestions | en, ja, de |
gl | Country used to bias results | us, in, gb |
ie / oe | Input and output character encoding | utf-8 |
Common errors and fixes
| Error | Cause | Fix |
|---|---|---|
NameError: name 'unicode' is not defined | You ran the Python 2 script on Python 3 | Use the corrected script and remove the unicode() call |
TypeError when no query is given | nargs='?' lets query be None | Make the argument required, as in the corrected version |
ModuleNotFoundError: No module named 'lxml' | The dependency isn't installed in the active environment | pip install lxml, or use the JSON variant |
ValueError: Unicode strings with encoding declaration are not supported | A str containing an XML declaration was passed to lxml | Pass r.content (bytes) to etree.fromstring |
XMLSyntaxError or JSONDecodeError | Google returned an HTML page (consent page, block page or error) instead of suggestions | Print r.status_code and the first part of r.text to see what came back, then slow down or change networks |
| HTTP 429 or 403 | Too many requests in a short time | Add delays between requests and cache the results |
| Garbled non-English characters | The response was decoded with the wrong charset | Send oe=utf-8 and decode the bytes as UTF-8 |
Collecting suggestions for keyword research
A common use is to expand a seed keyword by adding each letter of the alphabet and collecting the unique suggestions. The loop below reuses get_suggestions() from the JSON version and pauses between calls so it doesn't hammer the endpoint.
import string
import time
seed = "devops"
results = set()
for letter in string.ascii_lowercase:
for s in get_suggestions(f"{seed} {letter}"):
results.add(s)
time.sleep(1) # be polite; avoid triggering throttling
for s in sorted(results):
print(s)Code language: PHP (php)
Note: Keep the request volume low and respect Google's Terms of Service. For large-scale or commercial keyword data, use an officially supported data source rather than this undocumented endpoint.
Frequently asked questions
Does Google have an official autocomplete API?
Google doesn't offer the suggest endpoint as a documented, supported public API. The URLs used here are the ones its search box calls, so their format and availability can change without notice.
Do I need an API key to use Google Suggest?
No. The endpoint takes a plain HTTP GET request with no authentication. It can throttle or block clients that send too many requests.
How do I get suggestions in another language or for another country?
Set the hl parameter to a language code such as ja or de, and optionally set gl to a country code such as in or us. In the corrected script, use the --lang and --country options.
Why does the original script fail with NameError: unicode?
unicode() is a Python 2 built-in that Python 3 removed. In Python 3, command-line arguments are already Unicode strings, so you can drop the conversion.
Should I use the JSON or the XML endpoint?
The JSON endpoint (suggestqueries.google.com with client=firefox) is simpler because it needs only requests and the standard json module. Use the XML output=toolbar format only if existing code already depends on it.
Related tutorials
- More Programming & Development tutorials
- Huge collection of web reference for Patterns of Scalable, Reliable, and Performant Large-Scale Systems
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services โ all in one place.
Explore Hospitals