MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Google Suggest API Paython Code Example

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 raises NameError: name 'unicode' is not defined. In Python 3, command-line arguments are already str, so you don't need to convert them.
  • nargs='?' makes the query optional. If you run the script without an argument, args.query is None and 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 of https://.
  • etree.XML(r.text) passes a decoded string to lxml. If the response includes an XML encoding declaration, lxml raises ValueError: 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.
  • pprint is imported but never used.

Prerequisites

  • Python 3 (any currently supported release).
  • The requests library. Install lxml only 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

ParameterPurposeExample
qThe partial search text to completedevops
clientChooses the response format on suggestqueries.google.com. firefox returns a plain JSON arrayfirefox
outputChooses the response format on www.google.com/complete/search. toolbar returns XMLtoolbar
hlLanguage of the suggestionsen, ja, de
glCountry used to bias resultsus, in, gb
ie / oeInput and output character encodingutf-8

Common errors and fixes

ErrorCauseFix
NameError: name 'unicode' is not definedYou ran the Python 2 script on Python 3Use the corrected script and remove the unicode() call
TypeError when no query is givennargs='?' lets query be NoneMake the argument required, as in the corrected version
ModuleNotFoundError: No module named 'lxml'The dependency isn't installed in the active environmentpip install lxml, or use the JSON variant
ValueError: Unicode strings with encoding declaration are not supportedA str containing an XML declaration was passed to lxmlPass r.content (bytes) to etree.fromstring
XMLSyntaxError or JSONDecodeErrorGoogle returned an HTML page (consent page, block page or error) instead of suggestionsPrint r.status_code and the first part of r.text to see what came back, then slow down or change networks
HTTP 429 or 403Too many requests in a short timeAdd delays between requests and cache the results
Garbled non-English charactersThe response was decoded with the wrong charsetSend 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

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
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.

Related Posts

Python Tutorials: Files Operations using OS Module

Python's built-in os module lets a script work with the operating system: it can find and change the working directory, create and remove directories, rename and delete…

Read More

Python Example Code: Find all the pairs of numbers which sum upto `k`

This page shows how to find every pair of numbers in a Python list that adds up to a target value k, a common coding-interview question. The…

Read More

Python Example Code: Program for printing k largest elements in an array

To print the k largest elements of a Python list, you can sort it in descending order and take the first k items. That is what the…

Read More

Python Tutorials: Namesapce in Python with example

A namespace in Python maps names to objects. Python has four kinds: built-in, global (module), enclosing and local. Scope decides which of these namespaces Python searches when…

Read More

How to generate Letsencrypt certificates with Verifying domain using API

acme.sh can get a Let's Encrypt certificate by proving you control a domain through your DNS provider's API. It creates a temporary TXT record, so you never…

Read More

dotcover: dotcover print coverage results using cmd line

To print dotCover coverage results on the command line, run your tests with dotcover cover to create a snapshot, turn that snapshot into a JSON report with…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x