Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## [0.82.0] - 2026-11-23

### Added
- `google.search.search()` and `google.search.light()`: an `organic_results` item whose `link` is still a Google redirect (`https://www.google.com/goto?url=...`) now also has `link_token` (string) and `retry_after_seconds` (int, 0 = can be resolved right away). Both are `None` when `link` is already the real URL. The responses are plain dicts, so no call changes.
- `google.search.resolve(results)` makes one `POST /v1/google/resolve` request and returns `{"results": [...], "retry_after_seconds": int | None}`. It takes 1 to 25 rows, each with a `link_token`; other fields are returned unchanged, so `organic_results` items can be sent as they are. Each returned row is resolved (`link` is the result's own URL, no `link_token`), not ready (`link_token` and `retry_after_seconds`; the token can differ from the one sent, always keep the latest) or failed (`link_token` and `error`; do not send it again). Costs no credits.
- `google.search.resolve_all(results, *, max_wait=240.0)` calls `resolve` in requests of at most 25 rows, sleeps the `retry_after_seconds` the API returns (at least 1 second) and repeats until no row is waiting or `max_wait` seconds have passed. It returns a new list in the input order and does not change the input. Rows without a `link_token` are returned as they are and never sent. Rows that are still not ready at `max_wait` are returned with their latest `link_token` and `retry_after_seconds`; no exception is raised for them.
- Google limits how fast the links of one result page can be followed. Polling this way, all ten links of a page are usually known 45 to 70 seconds after the search.

## [0.81.0] - 2026-11-18

### Added
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ The official Python SDK for [ScrapeBadger](https://scrapebadger.com) - async web
- **Resilient retries** - Exponential backoff on transient errors
- **Async requests and webhooks** - Submit any slow call, poll or `wait` for it, or take a signed webhook; idempotency keys make re-submits safe
- **37+ Twitter endpoints** - Tweets, users, lists, communities, trends, geo, real-time streams
- **20 Google product APIs** - Search (with optional deferred AI Overview follow-up), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center**
- **20 Google product APIs** - Search (with optional deferred AI Overview follow-up and free result link resolution), Maps, News, Hotels, Trends (incl. topic autocomplete), Jobs, Shopping (+ merchant URL enrichment), Patents, Scholar (search + profiles + author + author citation + cite formats), Images, Videos, Finance, AI Mode, Lens, **Local Pack**, **Shorts**, **Flights**, Products, **Ads Transparency Center**
- **Vinted scraping** - Search items, item details, user profiles, brands, colors, markets
- **Reddit scraping** - Search posts/subreddits/users/domains, subreddit posts, post comments, user profiles, trophies, wiki pages, moderators
- **Web scraping** - Anti-bot bypass, JS rendering, screenshots, and selector/AI data extraction
Expand Down
92 changes: 90 additions & 2 deletions docs/google.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ async with ScrapeBadger(api_key="your-key") as client:
)
# Structured sections:
# serp["organic_results"] — position, title, link, snippet, displayed_link,
# date, sitelinks, rich_snippet, read_more_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
Expand Down Expand Up @@ -73,6 +75,89 @@ 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()` and `light()` 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.

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.

```python
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.

```python
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.

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

```python
Expand Down Expand Up @@ -353,6 +438,8 @@ look-alikes and lists the `variants` it searched.
| Sub-client | Method | Description |
|---|---|---|
| `search` | `search(q, *, gl, hl, num, start, domain, device, ...)` | Web search with 21 parameters |
| `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 |
Expand Down Expand Up @@ -387,7 +474,7 @@ look-alikes and lists the `variants` it searched.
| `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.
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

Expand All @@ -400,6 +487,7 @@ All methods are async and return `dict[str, Any]` responses matching the documen
| `ads/search` | **25** |
| `ads/advertisers` with `fuzzy=true` (billed as 3 lookups) | **45** |
| `shopping/product`, `shopping/product/click` | **1** |
| `resolve` (`/v1/google/resolve`) | **0** |
| Failed requests | **0** |

Prices change; `GET /api/public/pricing` (or the [pricing page](https://scrapebadger.com/pricing)) always has the live per-endpoint cost.
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "scrapebadger"
version = "0.81.0"
version = "0.82.0"
description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more"
readme = "README.md"
license = { text = "MIT" }
Expand Down
2 changes: 1 addition & 1 deletion src/scrapebadger/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1356,7 +1356,7 @@ async def main():
ZestimateHistoryPoint as ZillowZestimateHistoryPoint,
)

__version__ = "0.81.0"
__version__ = "0.82.0"

__all__ = [
# TikTok core models
Expand Down
2 changes: 1 addition & 1 deletion src/scrapebadger/_internal/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
T = TypeVar("T")

# User agent for SDK requests
SDK_VERSION = "0.81.0"
SDK_VERSION = "0.82.0"
USER_AGENT = f"scrapebadger-python/{SDK_VERSION}"


Expand Down
143 changes: 141 additions & 2 deletions src/scrapebadger/google/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,23 @@

from __future__ import annotations

import asyncio
from time import monotonic
from typing import TYPE_CHECKING, Any, Literal, overload

if TYPE_CHECKING:
from scrapebadger._internal.client import BaseClient

# POST /v1/google/resolve takes 1 to 25 rows per request.
_RESOLVE_MAX_ROWS = 25
# resolve_all() waits at least this long between two rounds of requests.
_RESOLVE_MIN_WAIT_S = 1.0


def _is_waiting(row: dict[str, Any]) -> bool:
"""True when a row has a ``link_token`` to send and has not failed."""
return bool(row.get("link_token")) and row.get("error") is None


class SearchClient:
"""Client for Google Web Search.
Expand All @@ -16,6 +28,9 @@ class SearchClient:
serp = await client.google.search.search("python 3.13")
for result in serp["organic_results"]:
print(result["title"], result["link"])

# Some links are still Google redirects: get the real URLs (free).
results = await client.google.search.resolve_all(serp["organic_results"])
```
"""

Expand Down Expand Up @@ -332,7 +347,11 @@ async def search(
organic_results_state
- `organic_results`: position/title/link/snippet/displayed_link,
plus `date`, `sitelinks`, `rich_snippet` and `read_more_link`
when Google shows them
when Google shows them. A result whose `link` is still a
Google redirect also has `link_token` and
`retry_after_seconds` (0 = can be resolved right away); both
are ``None`` when `link` is already the real URL. Pass the
results to :meth:`resolve_all` to get the real URLs.
- `ads`, `knowledge_graph`, `related_searches`,
`people_also_search_for`
- `related_questions`: question, rank, `type` (``"ai_overview"``
Expand Down Expand Up @@ -679,7 +698,9 @@ async def light(
pagination}`` — no ``ai_overview`` / ``knowledge_graph`` /
``ads`` / ``local_results`` / ``news_results`` blocks.
``search_information.organic_results_state`` is filled, as on
full Search.
full Search. ``organic_results`` items carry ``link_token`` and
``retry_after_seconds`` as on full Search; pass them to
:meth:`resolve_all` to get the real URLs.
"""
params: dict[str, Any] = {
"google_domain": google_domain,
Expand Down Expand Up @@ -732,3 +753,121 @@ async def light(
body, _, _ = await self._client.get_raw("/v1/google/light/search", params=params)
return body.decode("utf-8")
return await self._client.get("/v1/google/light/search", params=params)

async def resolve(self, results: list[dict[str, Any]]) -> dict[str, Any]:
"""Get the real URLs of results whose ``link`` is a Google redirect.

Calls ``POST /v1/google/resolve`` once. Costs no credits.

A result from :meth:`search` or :meth:`light` whose ``link`` is still
a Google redirect (``https://www.google.com/goto?url=...``) has a
``link_token``. Google limits how fast the links of one result page
can be followed, so a row can come back not ready, with the number of
seconds to wait. :meth:`resolve_all` does the waiting and retrying
for you.

Args:
results: 1 to 25 rows. Each row needs a non-empty string
``link_token``. Any other fields are returned unchanged on
the row, so ``organic_results`` items can be sent as they
are.

Returns:
``{"results": [...], "retry_after_seconds": int | None}``. The
rows come back in the order sent. Each row is one of:

- resolved: ``link`` is the result's own URL. The row has no
``link_token``, ``retry_after_seconds`` or ``error``.
- not ready: the row has ``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
sent: always keep the latest. ``link`` is as sent.
- failed: the row has ``link_token`` as sent and ``error`` (a
string). Do not send it again.

The top-level ``retry_after_seconds`` is the smallest wait among
the not-ready rows, or ``None`` when no row is waiting. Sending
a token before its wait is over is not an error: the row comes
back not ready with the wait that is left.

Raises:
ValidationError: 422 for an empty list, more than 25 rows, or a
row without ``link_token``.
ServerError: 503 when link resolution is temporarily
unavailable. The SDK retries it first, like other 5xx.
"""
return await self._client.post("/v1/google/resolve", json={"results": results})

async def resolve_all(
self, results: list[dict[str, Any]], *, max_wait: float = 240.0
) -> list[dict[str, Any]]:
"""Resolve every result link, waiting between requests as the API asks.

Calls :meth:`resolve` with the rows that have a ``link_token``, at
most 25 per request, then sleeps the smallest ``retry_after_seconds``
returned (at least 1 second) and sends the rows that are still not
ready again. It stops when no row is waiting or when ``max_wait``
seconds have passed. Costs no credits.

Polling this way, all ten links of a result page are usually 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.

Args:
results: Result rows, normally a search response's
``organic_results``. Rows without a ``link_token`` are
returned as they are and never sent. The list and its rows
are not modified.
max_wait: Stop after this many seconds (default 240). The last
sleep is cut so that it does not pass this limit. With 0,
each row is sent once.

Returns:
A new list with one row per input row, in the same order. Each
row that had a ``link_token`` is in one of the states described
in :meth:`resolve`:

- resolved: ``link`` is the result's own URL.
- failed: the row has ``error``. It is not sent again.
- not ready: ``max_wait`` passed first. The row has its latest
``link_token`` and ``retry_after_seconds``, so you can pass it
to :meth:`resolve` or :meth:`resolve_all` later. No exception
is raised for these rows.

Raises:
ScrapeBadgerError: A request failed (see :meth:`resolve`).

Example:
```python
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("failed:", result["error"])
elif result.get("link_token"):
print("not ready, wait", result["retry_after_seconds"], "s")
else:
print(result["link"])
```
"""
rows = [dict(row) for row in results]
deadline = monotonic() + max_wait
waiting = [i for i, row in enumerate(rows) if _is_waiting(row)]
while waiting:
waits: list[float] = []
for start in range(0, len(waiting), _RESOLVE_MAX_ROWS):
chunk = waiting[start : start + _RESOLVE_MAX_ROWS]
response = await self.resolve([rows[i] for i in chunk])
for i, row in zip(chunk, response.get("results") or [], strict=False):
if isinstance(row, dict):
rows[i] = row
wait = response.get("retry_after_seconds")
if isinstance(wait, int | float):
waits.append(wait)
waiting = [i for i in waiting if _is_waiting(rows[i])]
remaining = deadline - monotonic()
if not waiting or remaining <= 0:
break
delay = max(min(waits, default=_RESOLVE_MIN_WAIT_S), _RESOLVE_MIN_WAIT_S)
await asyncio.sleep(min(delay, remaining))
return rows
Loading
Loading