Skip to content

Latest commit

 

History

History
571 lines (476 loc) · 23.9 KB

google.md

File metadata and controls

571 lines (476 loc) · 23.9 KB

Google API

The ScrapeBadger Google API provides structured JSON access to 16 Google product APIs across 30 endpoints: Search, Maps, News, Hotels, Trends, Jobs, Shopping, Patents, Scholar, Autocomplete, Images, Videos, Finance, AI Mode, Lens, and immersive Products. All methods are available via client.google.

The service handles SearchGuard, proxy rotation, cookie warmup, and IP rotation on 429s automatically — you just call the endpoint.

Back to main README

Usage Examples

Web Search (SERP)

async with ScrapeBadger(api_key="your-key") as client:
    # Basic search
    serp = await client.google.search.search("python 3.13")
    for result in serp["organic_results"]:
        print(result["title"], result["link"])

    # Search with advanced parameters (21 supported)
    serp = await client.google.search.search(
        "best laptops 2026",
        gl="gb",
        hl="en",
        num=20,
        start=10,
        domain="google.co.uk",  # any of 185 Google domains
        device="mobile",
        tbs="qdr:w",  # past week
        safe="off",
    )
    # Structured sections:
    #   serp["organic_results"]      — position, title, link, snippet, displayed_link,
    #                                  date, sitelinks, rich_snippet, read_more_link,
    #                                  link_token, retry_after_seconds (see
    #                                  "Resolving result links" below)
    #   serp["knowledge_graph"]      — title, type, description, attributes
    #   serp["ai_overview"]          — text_blocks (paragraph/heading/list, with
    #                                  reference_indexes), references, videos
    #   serp["related_questions"]    — People Also Ask: question, rank, type
    #   serp["shopping_results"]     — carousel products with prices and IDs
    #   serp["perspectives"], serp["discussions_and_forums"],
    #   serp["short_videos"], serp["things_to_know"]
    #   serp["related_searches"]     — query, link
    #   serp["pagination"]           — current, next, page_no map
    print(f"About {serp['search_information']['total_results']:,} results "
          f"in {serp['search_information']['time_taken']}s")

People Also Ask answers

Google loads a People Also Ask answer only when the question is clicked, so a plain search returns the questions without answers. expand_related_questions opens them during the same search (True = every question the page shows, usually four; an integer N = the first N):

async with ScrapeBadger(api_key="your-key") as client:
    serp = await client.google.search.search(
        "are noise cancelling headphones worth it",
        expand_related_questions=2,
    )
    for q in serp["related_questions"]:
        if q["text_blocks"] is None:
            continue  # not opened, or the answer did not come back
        print(q["question"])
        for block in q["text_blocks"]:
            print("  ", block.get("snippet"))
        for ref in q["references"]:
            print("   source:", ref["title"], ref["link"])

Each answered question bills as one more Search request (credits = 20 x (1 + answered) at today's price); a question that does not come back is not billed. It adds about a second per question and upgrades mode="fast" to full. Light Search does not accept it.

Resolving result links

Google can return a result's URL as a redirect link (https://www.google.com/goto?url=...) instead of the page's own URL. In search() responses, each organic_results item whose link is still a redirect has two more fields:

Field Type Meaning
link_token str or None Send it to resolve() to get the real URL.
retry_after_seconds int or None Seconds to wait before resolving. 0 means it can be resolved right away.

Both are None when link is already the real URL. light() results always have the result's own URL in link, so they need no resolving.

Google limits how fast the links of one result page can be followed, so not every link is ready at once. resolve_all() sends the results, waits as long as the API asks, and repeats until every link is known. Resolving costs no credits.

import asyncio

from scrapebadger import ScrapeBadger


async def main() -> None:
    async with ScrapeBadger(api_key="your-key") as client:
        serp = await client.google.search.search("python 3.13")
        results = await client.google.search.resolve_all(serp["organic_results"])
        for result in results:
            if result.get("error"):
                print(result["position"], "failed:", result["error"])
            elif result.get("link_token"):
                print(result["position"], "not ready, wait", result["retry_after_seconds"], "s")
            else:
                print(result["position"], result["link"])


asyncio.run(main())

resolve_all(results, *, max_wait=240.0) returns a new list with one row per input row, in the same order. It does not change the list you pass in. Rows without a link_token are returned as they are and never sent. Each row that had a link_token comes back in one of three states:

State How to tell What to do
Resolved No link_token, no retry_after_seconds, no error link is the result's own URL.
Not ready link_token and retry_after_seconds (1 or more) Wait that many seconds, then send the row again. The token can differ from the one you sent: always keep the latest. link is as you sent it.
Failed link_token and error (a string) Do not send it again.

resolve_all() stops when no row is waiting or after max_wait seconds. It does not raise for rows that are still not ready at that point: they are returned with their latest link_token and retry_after_seconds, so you can pass them to resolve_all() or resolve() later.

Typical timing with resolve_all(): all ten links of a result page are known 45 to 70 seconds after the search. Once the result page is about 160 seconds old, every remaining link resolves in a single request.

resolve(results) makes one POST /v1/google/resolve request, for your own loop. It takes 1 to 25 rows, each with a link_token. Other fields on a row are returned unchanged, so organic_results items can be sent as they are.

async with ScrapeBadger(api_key="your-key") as client:
    serp = await client.google.search.search("python 3.13")
    pending = [r for r in serp["organic_results"] if r.get("link_token")]
    if pending:
        answer = await client.google.search.resolve(pending)
        for row in answer["results"]:  # same order as sent
            print(row["position"], row["link"], row.get("retry_after_seconds"))
        # Smallest wait among the rows that are not ready, or None when none is waiting
        print(answer["retry_after_seconds"])

Sending a token before its wait is over is not an error: the row comes back not ready with the wait that is left. An invalid request (no rows, more than 25, or a row without link_token) raises ValidationError (422). When link resolution is temporarily unavailable the API answers 503 with Retry-After; the SDK retries it and raises ServerError if it still fails.

Light Search

light() calls GET /v1/google/light/search: web results only, each with its own URL in link. It costs 10 credits per successful request (full Search costs 20) and typically answers in about a second. It takes the same parameters as search(), without ai_overview, expand_related_questions and mode.

async with ScrapeBadger(api_key="your-key") as client:
    serp = await client.google.search.light("python 3.13", num=20)
    for result in serp["organic_results"]:
        print(result["position"], result["title"], result["link"])

The response is small. Fields without a value are left out (there are no None values):

{
  "search_parameters": {
    "gl_requested": "us",
    "domain_requested": "google.com",
    "google_parameters": {"q": "python 3.13", "gl": "us", "hl": "en", "num": "10"}
  },
  "search_metadata": {
    "requested_device": "desktop",
    "custom_user_agent": false,
    "serp_quality": "ok",
    "organic_results_source": "lightweight"
  },
  "search_information": {
    "query_displayed": "python 3.13",
    "url": "https://www.google.com/search?q=python+3.13&gl=us&hl=en&num=10"
  },
  "organic_results": [
    {
      "position": 1,
      "title": "What's New In Python 3.13",
      "link": "https://docs.python.org/3/whatsnew/3.13.html",
      "displayed_link": "https://docs.python.org › whatsnew",
      "snippet": "This article explains the new features in Python 3.13, compared to 3.12.",
      "rank": 1,
      "page_rank": 1
    }
  ],
  "pagination": {"current": "1"}
}
Field Notes
search_parameters gl_requested, domain_requested and google_parameters (always q, gl, hl, num; start, safe, tbs, lr, cr, nfpr, filter, uule and the as_* parameters when given). location_requested, location_resolved, uule_requested, lat, lon and radius only when the request has them.
search_metadata requested_device (the device you sent, default "desktop"), custom_user_agent (whether user_agent was sent), serp_quality ("ok"), organic_results_source ("lightweight").
search_information query_displayed, and url: the Google search URL for the query.
organic_results position, title, link, displayed_link, snippet, rank, page_rank. rank and page_rank equal position. displayed_link and snippet can be missing on a result. [] when Google has no results for the query.
pagination current: the page number, as a string.
  • num can be 1 to 100. site: and inurl: work in q. location, uule, lat/lon/radius, gl, hl, start, safe, tbs, lr, cr, nfpr, filter and the as_* parameters all apply.
  • device and user_agent are accepted and echoed in search_metadata, but they do not change Light results.
  • output="html" returns Google's results page HTML as a string.
  • Ads, Knowledge Graph, AI Overview, People Also Ask, local pack, news, videos and related searches are not on Light. Use search() for them. tbm, a udm other than "14"/"web", ludocid, lsig, kgmid, ibp and uds raise ValidationError (422) on Light.
  • When results could not be fetched this time, the API answers 503 with Retry-After: 1. It is not billed. The SDK retries it, then raises ServerError.

Maps (Search, Place, Reviews, Photos, Posts)

async with ScrapeBadger(api_key="your-key") as client:
    # Search for places
    places = await client.google.maps.search(
        "coffee shops in san francisco",
        ll="@37.7749,-122.4194,14z",
    )
    for place in places["results"]:
        print(f"{place['title']} — {place['rating']}★ ({place['reviews_count']} reviews)")

    # Place details
    detail = await client.google.maps.place(data_id="0x808580a2:0x123abc")

    # Reviews (sorted + paginated)
    reviews = await client.google.maps.reviews(
        "0x808580a2:0x123abc",
        sort_by="newestFirst",
        results=20,
    )

    # Photos + business posts
    photos = await client.google.maps.photos("0x808580a2:0x123abc")
    posts = await client.google.maps.posts("0x808580a2:0x123abc")

News (Search, Topics, Trending)

async with ScrapeBadger(api_key="your-key") as client:
    # Article search
    articles = await client.google.news.search("openai gpt-5", max_results=20)
    for a in articles["articles"]:
        print(f"[{a['source']['name']}] {a['title']} ({a['published_at']})")

    # News by predefined topic
    tech = await client.google.news.topics("TECHNOLOGY")

    # Trending stories (real-time)
    trending = await client.google.news.trending(gl="US")

Hotels

async with ScrapeBadger(api_key="your-key") as client:
    hotels = await client.google.hotels.search(
        "Paris",
        check_in="2026-05-01",
        check_out="2026-05-05",
        adults=2,
        currency="EUR",
    )
    for prop in hotels["properties"]:
        rate = prop.get("rate_per_night", {}).get("extracted")
        print(f"{prop['name']} — {rate} {hotels.get('currency', 'EUR')}")

    # Detailed property info using the property_token from search
    detail = await client.google.hotels.details(
        hotels["properties"][0]["property_token"],
        check_in="2026-05-01",
        check_out="2026-05-05",
    )

Trends (Interest, Regions, Related, Trending)

async with ScrapeBadger(api_key="your-key") as client:
    # Interest over time — up to 5 comma-separated terms
    interest = await client.google.trends.interest(
        "python,javascript,rust,go,java",
        geo="US",
        date="today 12-m",
    )
    for point in interest["timeline"]:
        print(point["date"], point["values"])

    # Interest by region
    regions = await client.google.trends.regions("python", geo="")

    # Related topics + queries
    related = await client.google.trends.related("python")
    print("Rising queries:", [q["query"] for q in related["related_queries"]["rising"]])

    # Real-time trending
    trending = await client.google.trends.trending(geo="US")

Jobs

async with ScrapeBadger(api_key="your-key") as client:
    jobs = await client.google.jobs.search(
        "software engineer",
        location="San Francisco, CA",
        job_type="FULLTIME",
        date_posted="week",
    )
    for job in jobs["jobs"]:
        print(f"{job['title']} @ {job['company_name']} — {job['location']}")

Shopping (Search + Seller Offers + Product Detail)

async with ScrapeBadger(api_key="your-key") as client:
    # Step 1: search
    products = await client.google.shopping.search(
        "laptop",
        min_price=500,
        max_price=2000,
        sort_by="price_low",
    )
    for p in products["results"]:
        print(f"{p['title']} — {p['price']['extracted']} from {p['source']} "
              f"({p['rating']}★, {p['reviews']})")

    # Step 2: full product detail with merchant offers. Pass the tile's
    # gpcid plus the query that surfaced it.
    first = products["results"][0]
    detail = await client.google.products.detail(
        first["gpcid"], q="laptop", include_offers=True
    )

    # Multi-seller prices by the tile's catalog_id.
    offers = await client.google.shopping.offers(catalog_id=first["catalog_id"], gl="us")

    # Multi-seller prices by barcode (GTIN-8/UPC-A/EAN-13/GTIN-14).
    # Resolves the barcode to a product, then returns its Shopping offers.
    offers = await client.google.shopping.offers("0190198001751", gl="us")
    print(offers["product_title"])
    for o in offers["offers"]:
        print(f"{o['source']} — {o['price']['extracted']}")

Patents

async with ScrapeBadger(api_key="your-key") as client:
    results = await client.google.patents.search(
        "distributed lock manager",
        assignee="Google",
        sort="new",
    )
    for patent in results["results"]:
        print(f"{patent['patent_id']}: {patent['title']}")

    # Full patent detail (abstract, claims, citations, classifications)
    detail = await client.google.patents.detail("US10123456B2")
    print(detail["abstract"])
    print("Claims:", len(detail["claims"]))

Scholar

async with ScrapeBadger(api_key="your-key") as client:
    papers = await client.google.scholar.search(
        "transformer attention mechanism",
        as_ylo=2020,
        as_yhi=2024,
        num=20,
    )
    for paper in papers["results"]:
        print(f"{paper['title']} ({paper.get('cited_by_count', 0)} citations)")

Autocomplete, Images, Videos

async with ScrapeBadger(api_key="your-key") as client:
    # Search suggestions
    suggestions = await client.google.autocomplete.get("pyth")
    print(suggestions["suggestions"])

    # Image search with size + color filters
    images = await client.google.images.search(
        "golden retriever",
        imgsz="l",        # large
        imgcolor="color",
        imgtype="photo",
    )

    # Video search
    videos = await client.google.videos.search("python async tutorial", tbs="qdr:w")

Finance, AI Mode, Lens, Products

async with ScrapeBadger(api_key="your-key") as client:
    # Stock / index / crypto quotes
    quote = await client.google.finance.quote("AAPL:NASDAQ")
    print(f"{quote['symbol']}: {quote['price']} ({quote['change']}%)")

    # AI-generated answers (udm=50)
    ai_answer = await client.google.ai_mode.search("what is kubernetes?")
    for block in ai_answer["text_blocks"]:
        print(block["snippet"])
    for ref in ai_answer["references"]:
        print("Source:", ref["title"], ref["link"])

    # Localise "near me" answers: one of location, uule, or lat + lon.
    # With location and no gl, gl becomes the location's country ("kr").
    local = await client.google.ai_mode.search(
        "best coffee near me", location="Wonju-si,Gangwon-do,South Korea", hl="ko"
    )
    print(local["location"]["resolved"], local["country"])
    busan = await client.google.ai_mode.search("맛집 추천", lat=35.1763, lon=129.0798, gl="kr")
    print(busan["markdown"])

    # Visual image search by URL
    lens = await client.google.lens.search("https://example.com/photo.jpg")

    # Immersive product detail (by product_id)
    product = await client.google.products.detail("1234567890")

Ads Transparency Center

async with ScrapeBadger(api_key="your-key") as client:
    # Free-text ad search is domain-based: resolve a brand name to IDs first.
    found = await client.google.ads.search_advertisers("rufwear", fuzzy=True)
    for row in found["advertisers"]:
        print(row["name"], row["advertiser_id"], row["similarity"], row["matched_query"])

    advertiser_id = found["advertisers"][0]["advertiser_id"]
    ads = await client.google.ads.search(advertiser_id=advertiser_id, format="VIDEO")
    first = ads["creatives"][0]
    creative = await client.google.ads.creative(advertiser_id, first["creative_id"])

    # Disclosed spend, ad-format mix and per-day spend for one region
    spend = await client.google.ads.advertiser(advertiser_id, region="US")

search_advertisers returns up to num=3000 advertisers in one call (they do not page) plus up to num_domains=100 domain rows, which page with next_page_token → cursor. fuzzy=True also finds misspellings and look-alikes and lists the variants it searched.

API Reference

Sub-clients

Sub-client Description
client.google.search Google web search (SERP)
client.google.maps Maps: search, place, reviews, photos, posts
client.google.news News: search, topics, trending
client.google.hotels Hotels: search, details
client.google.trends Trends: interest, regions, related, trending
client.google.jobs Job listings search
client.google.shopping Shopping: search, seller offers
client.google.patents Patents: search, detail
client.google.scholar Academic paper search
client.google.autocomplete Search suggestion lookup
client.google.images Image search
client.google.videos Video search
client.google.finance Stock / index / crypto quotes
client.google.ai_mode Generative AI answers (udm=50)
client.google.lens Visual image search by URL
client.google.products Immersive product detail
client.google.ads Ads Transparency Center: creatives, advertisers, spend

Methods

Sub-client Method Description
search search(q, *, gl, hl, num, start, domain, device, ...) Web search with 21 parameters
search light(q, *, gl, hl, num, start, domain, location, ...) Light Search: web results only, each with its own URL
search resolve(results) Real URLs for up to 25 results with a link_token, one request (free)
search resolve_all(results, *, max_wait) Resolve every result link, waiting and retrying as needed (free); returns a list
maps search(q, *, ll, gl, hl, start) Place search by query
maps place(*, place_id, data_id, hl, gl) Place detail
maps reviews(data_id, *, sort_by, hl, next_page_token, results) Paginated reviews
maps photos(data_id, *, hl, next_page_token) Place photos
maps posts(data_id, *, next_page_token) Business posts
news search(q, *, hl, gl, max_results) News article search
news topics(topic, *, hl, gl, max_results) News by topic
news trending(*, hl, gl, max_results) Trending stories
hotels search(q, *, check_in, check_out, adults, currency, gl) Hotel search
hotels details(property_token, *, check_in, check_out) Property details
trends interest(q, *, geo, date) Interest over time
trends regions(q, *, geo) Interest by region
trends related(q, *, geo) Related topics + queries
trends trending(*, geo) Real-time trending
jobs search(q, *, location, gl, job_type, date_posted) Job listings
shopping search(q, *, gl, min_price, max_price, sort_by) Product search
shopping offers(barcode, *, gl, hl, catalog_id) Multi-seller prices by barcode or catalog id
patents search(q, *, page, num, sort, inventor, assignee) Patent search
patents detail(patent_id) Patent document
scholar search(q, *, hl, as_ylo, as_yhi, as_sdt, page, num) Academic papers
autocomplete get(q, *, hl, gl) Search suggestions
images search(q, *, gl, hl, tbs, imgsz, imgcolor, imgtype, safe, page) Image search
videos search(q, *, gl, hl, tbs, safe, page) Video search
finance quote(q, *, hl) Stock/index/crypto quote
ai_mode search(q, *, gl, hl, include_html, location, uule, lat, lon) AI-generated answer, optionally localised
lens search(url, *, gl, hl) Visual search by URL
products detail(product_id, *, gl, hl) Immersive product
ads search(query, *, advertiser_id, region, format, start_date, end_date, num, cursor) Ad creatives
ads search_advertisers(query, *, num, num_domains, country, fuzzy, cursor) Advertiser IDs by name or domain
ads advertiser(advertiser_id, *, region, start_date, end_date) Disclosed spend and ad mix
ads creative(advertiser_id, creative_id, *, region, political) One creative with variations

All methods are async and return dict[str, Any] responses matching the documented JSON shapes, except search.resolve_all, which returns a list of result rows.

Credit Costs

Endpoint Credits
light (/v1/google/light/search) 10
search, images, videos, shorts, local, ai-mode/search, ai-overview, lens/search, autocomplete, maps/*, news/*, trends/*, jobs/search, scholar/*, patents/*, finance/quote, hotels/*, flights/*, shopping/search, products/detail 20
shopping/offers 25
ads/advertisers, ads/advertiser, ads/creative 15
ads/search 25
ads/advertisers with fuzzy=true (billed as 3 lookups) 45
resolve (/v1/google/resolve) 0
Failed requests 0

Prices change; GET /api/public/pricing (or the pricing page) always has the live per-endpoint cost.

Anti-Bot Handling

Google deployed SearchGuard in January 2025 — a JavaScript challenge that blocks raw HTTP. The ScrapeBadger Google scraper handles it automatically:

  1. First request attempts curl_cffi with cached cookies (~0.2s fast path)
  2. On SearchGuard detection, a patchright browser warmup solves the challenge
  3. Subsequent requests reuse the warm cookies for speed
  4. On 429 or CAPTCHA, the cached residential proxy session is invalidated to rotate the exit IP (up to 3 rotations per request)

See the full API documentation for complete details on every endpoint, including Pydantic response schemas and all parameters.


Back to main README