Scrape Google Search Results with Python
To scrape Google search results with Python, you can fetch google.com with requests and parse the HTML with BeautifulSoup, or call a search endpoint that returns the results page as JSON. The first route means maintaining selectors against markup you don't control. The second is one GET /v1/google-search/search call with a query, which returns organic_results, related_questions (People also ask) and related_searches as named fields for 1 credit. This guide shows the Python for the second route, the parameters, a recorded response, pagination and the cost.
Why does requests plus BeautifulSoup on google.com break?
A homemade Google scraper breaks because every part of it depends on things outside your code. Your parser finds results by HTML structure and class names that you didn't write, that nobody documents for you, and that can change between one run and the next. When they do, the selectors match nothing and the script returns an empty list without raising an error, so the failure is silent.
The second weak point is the response itself. Your script has to decide whether the HTML it received is a results page at all. If it gets back a consent form, a challenge page or a CAPTCHA instead, the same selectors also find nothing, and the only way to tell those cases apart is more parsing code. A challenge page is a signal to stop. Don't try to get around it with rotating proxies or CAPTCHA solvers, and read Google's terms of service before you automate anything against google.com.
Then there's the work that isn't parsing: pacing requests, retrying, logging how many results each page returned so you notice when it drops to zero, and reading positions correctly when maps, questions and other blocks sit above the first organic link. Web Scraping with Python builds a requests and BeautifulSoup scraper for a practice site and covers when to stop maintaining one. For Google, the alternative is to ask for the page as JSON.
How do you get Google results as JSON in Python?
Send a GET request to https://api.perceptlayer.com/v1/google-search/search with your search terms in query and your API key in the X-API-Key header. The response is the results page broken into named fields, so the Python is a request and a few dictionary lookups, with no HTML parsing and no selectors. Here is the call as cURL first:
curl "https://api.perceptlayer.com/v1/google-search/search?query=best+restaurants+in+Berlin&hl=en&safe=off" \
-H "X-API-Key: $API_KEY"
The same request in Python, reading organic results, People also ask questions and related searches:
import os
import requests
API = "https://api.perceptlayer.com"
HEADERS = {"X-API-Key": os.environ["API_KEY"]}
def google_search(query, **params):
resp = requests.get(
f"{API}/v1/google-search/search",
params={"query": query, **params},
headers=HEADERS,
timeout=60,
)
if resp.status_code != 200:
try:
error = resp.json().get("error", {})
except ValueError: # a body that isn't JSON
error = {}
raise RuntimeError(f"{resp.status_code} {error.get('code')}: {error.get('message')}")
print("credits used:", resp.headers.get("X-Credits-Used"),
"remaining:", resp.headers.get("X-Credits-Remaining"))
return resp.json()
data = google_search("best restaurants in Berlin", hl="en", safe="off")
for result in data.get("organic_results", []):
print(result["position"], result["title"], result["link"])
for item in data.get("related_questions", []):
print("People also ask:", item["question"])
for item in data.get("related_searches", []):
print("Related search:", item["query"])
Use .get() for the blocks. A results page only has a People also ask box or local results for some queries, so code that indexes data["related_questions"] directly will fail on the queries without one. Keys start with sk_live_; the authentication docs cover the header and the api_key query parameter for clients that can't send headers.
Which parameters does the search endpoint take?
The search endpoint takes one required parameter, query, and 29 optional ones. The table lists the ones most search scripts reach for, with their types and the allowed values the catalogue gives. Nothing beyond these types and values is documented, so don't assume defaults or page sizes; test a value in the playground and compare the response with what you expected.
| Parameter | Type | Required | Allowed values or limits |
|---|---|---|---|
query |
string | yes | Your search terms |
hl |
string | no | Up to 2 characters; the recorded request used en |
gl |
string | no | Up to 2 characters |
location |
string | no | Up to 500 characters |
google_domain |
string | no | Up to 50 characters |
device |
string | no | desktop, tablet, mobile |
safe |
string | no | active, off; the recorded request used off |
tbm |
string | no | isch, vid, nws, lcl, shop, pts |
start |
integer | no | No range documented |
page |
integer | no | No range documented |
amount |
integer | no | No range documented |
nfpr |
integer | no | 0, 1 |
filter |
integer | no | 0, 1 |
include_thumbnails |
string | no | 0, 1, true, false |
The rest (uule, cr, lr, tbs, as_qdr, udm and others) are on the Search endpoint page. The Search Advanced endpoint takes the same parameters plus fetch_ai_overview, and the Google Search API page lists all seven endpoints, including Search Light and autocomplete.
What does the response contain?
The response is one JSON object per results page, with a top-level field for each block: search_information, organic_results, related_questions, related_searches, people_also_search_for, local_results, filters, pagination and serp_results, which records each block's type and absolute rank. This is the recorded response to the request above, trimmed with …:
{
"search_information": {
"query_displayed": "best restaurants in Berlin",
"organic_results_count": 6
},
"organic_results": [
{
"position": 1,
"title": "The Best Restaurants in Berlin - Food Guide & Map",
"link": "https://andershusa.com/best-restaurants-berlin-germany-guide/",
"displayed_link": "https://andershusa.com › best-restaurants-berlin-german...",
"snippet": "Dec 3, 2025 — Tim Raue is the most internationally renowned restaurant in Berlin. It holds two Michelin stars, …",
"source": "Anders & Kaitlin",
"rank_group": 1,
"rank_absolute": 4
},
…
],
"related_searches": [
{
"query": "Best restaurants in Berlin for tourists",
"link": "https://www.google.com/search?safe=off&gl=us&hl=en&complete=0&pws=0&nfpr=1&q=Best+restaurants+in+Berlin+for+tourists"
},
…
],
"related_questions": [
{
"question": "What is the coolest restaurant in Berlin?",
"next_page_token": "fc=EqEBCmJBSmlUNHRMWjV0cUtnRWF3THBmd2poWERESG9Zd1NDdjV1eVBaTnlyQUpwWHptbXpvWEl3cEcteUc4clBmTmM2RmVqZ3gxeFBSR2Q2YnhWUXRYTV9fbU9TZ25Oa3RSM2JJQRIXZlBEYWFyWDFHc1RtN…"
},
…
],
"pagination": [
{
"start": 10,
"link": "https://www.google.com/search?q=best+restaurants+in+Berlin&safe=off&gl=us&hl=en&complete=0&pws=0&nfpr=1&start=10&sstk=…"
},
…
],
…
}
| Field | What the recording holds |
|---|---|
organic_results[] |
position, title, link, redirect_link, displayed_link, snippet, snippet_highlighted_words, source, rank_group, rank_absolute |
related_questions[] |
question and a next_page_token |
related_searches[] |
query and link |
people_also_search_for[] |
name, query and link |
local_results.places[] |
title, rating, reviews, price, type, website, phone, address, hours |
pagination[] |
start and link |
Read positions with care. The first organic result has position 1 but rank_absolute 4, because local results sat above it on the page. If you report rankings, store both. SERP API: What It Returns and What a Query Costs compares this shape with the Bing and DuckDuckGo responses.
How do you get the second page of results?
The recorded response's pagination array lists further pages, each with a start value (10, then 20) and a Google link containing the same start. The search endpoint accepts a start parameter, and the names match, so passing a pagination[].start value back as start is the natural way to ask for the next page. No recording shows a second page yet, though, so treat this as untested and check one in the playground first.
Write the loop so it stops on its own if paging doesn't behave as expected. This version collects up to max_pages pages, deduplicates by link, and stops when the response lists no further start, or when a page adds no new links:
def collect_organic(query, max_pages=3, **params):
seen = {}
start = None
for _ in range(max_pages):
page_params = dict(params)
if start is not None:
page_params["start"] = start
data = google_search(query, **page_params)
new = 0
for result in data.get("organic_results", []):
if result["link"] not in seen:
seen[result["link"]] = result
new += 1
if new == 0:
break # nothing new: stop rather than pay for repeats
starts = [p["start"] for p in data.get("pagination", [])
if start is None or p["start"] > start]
if not starts:
break
start = min(starts)
return list(seen.values())
results = collect_organic("best restaurants in Berlin", max_pages=2, hl="en", safe="off")
print(len(results), "unique organic results")
Every page is a separate call at 1 credit, so max_pages=2 costs at most 2 credits per query. The endpoint also takes a page parameter; the recording doesn't show how it relates to start, so pick one and keep it consistent within a pull.
What does scraping Google results this way cost?
Each successful call costs 1 credit, and each call returns one results page, so the cost is queries × pages × runs. Failed calls cost nothing and return X-Credits-Used: 0, so a retry after a 429 or a 502 doesn't add to the bill. Every account gets 100 free credits after verifying an email address, with no credit card.
| Job | Calculation | Credits a month |
|---|---|---|
| 30 queries a day, first page | 30 × 1 × 30 | 900, inside the Starter pack's 10,000 |
| 100 queries a day, first page | 100 × 1 × 30 | 3,000, inside the Starter pack's 10,000 |
| 100 queries a day, two pages | 100 × 2 × 30 | 6,000, inside the Starter pack's 10,000 |
| 500 queries a day, two pages | 500 × 2 × 30 | 30,000, inside the Build pack's 50,000 |
Purchased credits last 12 months, and there's no subscription. See pricing for what credits cost and the credits docs for how the balance works.
Speed is set by your account's rate: 1 request a second on a free account, and at least 5 a second on a paying one. A 429 response carries Retry-After with the seconds to wait. At 5 requests a second, 3,000 searches take 10 minutes; Concurrent API Requests in Python shows how to run a batch at that rate without tripping the limit.
How do you handle errors in the script?
Every error returns an HTTP status and a JSON body with error.code, error.message and error.request_id, and no error costs credits. The google_search() function above raises on any non-200 status with the code and message, which is enough for a one-off script. A batch job should sort the errors into ones worth retrying and ones that need you.
Retry rate_limited (429) and temporarily_unavailable (503) after the Retry-After seconds, and source_error (502) after a short backoff. Stop on invalid_api_key (401), invalid_parameters (422) and insufficient_credits (402): the service is prepaid, nothing more is debited once the balance runs out, and there's no automatic top-up. One case does cost: a request whose reply was lost to a client timeout may have succeeded and been billed, because requests have no idempotency key. The errors docs list every code, and HTTP 429 Too Many Requests covers backoff.
Run best restaurants in Berlin, then a query of your own, in the playground on the Google Search API page and compare the response with your browser. When the fields fit, get a free API key and run the script above.
APIs in this post
Frequently asked questions
Is it legal to scrape Google search results?
It depends on your jurisdiction, how you collect the results and what you do with them, so read Google's terms of service before you automate anything against google.com. Store what you need, don't republish other sites' snippets wholesale, and don't collect personal data from results without a lawful basis. Data from the search endpoint is collected from publicly available sources and returned as found at the time of the call.
How many results does one call return?
One call returns one results page. In the recorded response for best restaurants in Berlin, search_information.organic_results_count is 6, alongside local results, People also ask questions and related searches. The count varies by query, and the catalogue doesn't document a page size, so read the length of organic_results rather than assuming one.
Can I get People also ask questions without the organic results?
Every search response that has a People also ask box includes it in related_questions, each with a question and a next_page_token. You pay the same 1 credit whether you read the questions, the organic results or both, so there's no saving in asking for less. Read the block you need and ignore the rest.
Does a failed search cost credits?
No. Only a successful response debits credits. A failed call returns an HTTP status, a JSON error with a code and a request_id, and X-Credits-Used: 0. The exception to watch is a client timeout: the request may have succeeded and been billed even though your script never saw the reply.
Can an AI agent search Google this way?
Yes. Through the MCP server at https://perceptlayer.com/mcp, an agent finds the endpoint with search_endpoints, reads its parameters with get_endpoint (both free) and runs it with call_endpoint, which spends credits only on success and reports the credits used and remaining. The AI agents docs cover setup.