From 1a6588a4e14d22736e2f98c207e7787d223aedec Mon Sep 17 00:00:00 2001 From: kasparasizi1 <132673909+kasparasizi1@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:26:02 +0200 Subject: [PATCH 1/2] feat(google): document the condensed Light Search response (0.89.0, SCR-774) GET /v1/google/light/search now returns each organic result's own URL in `link` and a smaller response with no null fields (scrape-badger/scrapebadger#3741). light() already calls that endpoint; this brings what the SDK says about it in line and tests the request. - light() docstring: the new response shape, the 422s for tbm / udm / ludocid / lsig / kgmid / ibp / uds, the 503 with Retry-After: 1 (not billed), and device / user_agent being echoed only. Signature unchanged. - resolve() docstring: only search() results carry link_token. - docs/google.md: a "Light Search" section, a methods-table row, and the link-resolving text limited to search(). - get_raw() leaves out None params, as JSON requests already did: output="html" sent every unset parameter as an empty value (lat=, tbm=, ...). - Tests: light() calls /v1/google/light/search with exactly its params, for JSON and HTML, and returns the condensed answer as is. - Version 0.89.0 and a CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 18 ++++ docs/google.md | 80 ++++++++++++++++- pyproject.toml | 2 +- src/scrapebadger/__init__.py | 2 +- src/scrapebadger/_internal/client.py | 5 +- src/scrapebadger/google/search.py | 129 ++++++++++++++++++--------- tests/test_google_targeting.py | 123 +++++++++++++++++++++++++ uv.lock | 2 +- 8 files changed, 310 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 064f879..a7da962 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## [0.89.0] - 2026-12-03 + +### Changed +- **`google.search.light()` returns each result's own URL and a smaller response.** This follows the Light Search API change (SCR-774). Every `organic_results` item's `link` is the result's own URL. Light no longer returns Google redirect links, so Light results have no `link_token` or `retry_after_seconds`, and there is nothing to pass to `resolve()` or `resolve_all()`. Fields without a value are left out of the response, so there are no `None` values. A typical answer takes about a second. The price is unchanged: 10 credits per successful request. +- The Light response now has `search_parameters` (`gl_requested`, `domain_requested`, `google_parameters`, and the location fields when the request has them), `search_metadata` (`requested_device`, `custom_user_agent`, `serp_quality`, `organic_results_source`), `search_information` (`query_displayed`, `url`), `organic_results` (`position`, `title`, `link`, `displayed_link`, `snippet`, `rank`, `page_rank`) and `pagination` (`current`, a string). `displayed_link` and `snippet` can be missing on a result. +- Removed from the Light response: + - `related_searches`. + - `search_information`: `total_results`, `time_taken`, `organic_results_state`. + - On each organic result: `highlighted_keywords`, `source`, `favicon`, `sitelinks`, `inline_sitelinks`, `date`, `rich_snippet`, `read_more_link`, `link_token`, `retry_after_seconds`. + - `pagination`: `next`, `total_results`, `total_pages`, `page_no`. + - The diagnostic fields in `search_metadata`, such as `fetch_source`. + + `google.search.search()` still has all of these, and its results still carry `link_token`. +- `light()`'s docstring and the Google guide (new "Light Search" section) describe the new response, the 422 for `tbm`, a `udm` other than `"14"`/`"web"`, `ludocid`, `lsig`, `kgmid`, `ibp` and `uds`, and the 503 with `Retry-After: 1` (not billed) when results could not be fetched. `device` and `user_agent` are accepted but do not change Light results. No signature changes; the response is still a plain dict. + +### Fixed +- `search()` and `light()` with `output="html"` sent every parameter left unset as an empty value (`lat=`, `tbm=`, ...). They now leave them out, as JSON requests always did. + ## [0.88.0] - 2026-12-02 ### Changed diff --git a/docs/google.md b/docs/google.md index a0cc1c7..9f55ad5 100644 --- a/docs/google.md +++ b/docs/google.md @@ -79,15 +79,16 @@ Search does not accept it. 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: +`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. +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 @@ -158,6 +159,78 @@ not ready with the wait that is left. An invalid request (no rows, more than 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`. + +```python +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): + +```json +{ + "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) ```python @@ -430,6 +503,7 @@ 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` | `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 | diff --git a/pyproject.toml b/pyproject.toml index 2f99dde..1c2f843 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "scrapebadger" -version = "0.88.0" +version = "0.89.0" description = "Official Python SDK for ScrapeBadger - Async web scraping APIs for Twitter and more" readme = "README.md" license = { text = "MIT" } diff --git a/src/scrapebadger/__init__.py b/src/scrapebadger/__init__.py index 6c20a1c..c085610 100644 --- a/src/scrapebadger/__init__.py +++ b/src/scrapebadger/__init__.py @@ -1357,7 +1357,7 @@ async def main(): ZestimateHistoryPoint as ZillowZestimateHistoryPoint, ) -__version__ = "0.88.0" +__version__ = "0.89.0" __all__ = [ # TikTok core models diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index bd071b7..ac140b4 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -59,7 +59,7 @@ _CONCURRENCY_ERRORS = frozenset({"concurrency_limit_exceeded", "trial_concurrency"}) # User agent for SDK requests -SDK_VERSION = "0.88.0" +SDK_VERSION = "0.89.0" USER_AGENT = f"scrapebadger-python/{SDK_VERSION}" @@ -542,6 +542,9 @@ async def get_raw( Raises: ScrapeBadgerError: For API errors. """ + # Leave out None values, as _request does; httpx would send them as empty strings. + if params: + params = {k: v for k, v in params.items() if v is not None} response = await self._execute_request("GET", path, params=params) if response.status_code >= 400: diff --git a/src/scrapebadger/google/search.py b/src/scrapebadger/google/search.py index 11eac96..6958eed 100644 --- a/src/scrapebadger/google/search.py +++ b/src/scrapebadger/google/search.py @@ -634,25 +634,52 @@ async def light( user_agent: str | None = None, output: Literal["json", "html"] = "json", ) -> dict[str, Any] | str: - """Google Light Search — organic results + related searches only. + """Google Light Search: organic results only, each with its own URL. - Calls the dedicated ``/v1/google/light/search`` endpoint, which is - billed at the Light rate (half of full :meth:`search`; query - ``/public/pricing`` for the live rate). Skips ads, Knowledge Graph, - AI Overview, People Also Ask, local pack, news, inline videos and - shopping. Use when you only need the 10 blue links. Has a 12-second - processing budget; past it the API returns ``503`` with - ``Retry-After: 60``. AI Overview and People Also Ask answers - (``ai_overview``, ``expand_related_questions``) need :meth:`search`. + Calls ``GET /v1/google/light/search``. Costs 10 credits per + successful request; failed requests (5xx) are not billed. A typical + answer takes about a second. + + Every organic result's ``link`` is the result's own URL. Light does + not return Google redirect links, so there is no ``link_token`` on + Light results and nothing to pass to :meth:`resolve_all`. + + Light returns web results only. Ads, Knowledge Graph, AI Overview, + People Also Ask, local pack, news, videos and related searches are + not on Light; use :meth:`search` for them. Args: + q: Search query. Google operators such as ``site:`` and + ``inurl:`` work. + gl: Country code (default "us"). + hl: Language code (default "en"). + num: Number of results (1-100). + start: Result offset (0, 10, 20, ...). + domain: Google domain (e.g. "google.com", "google.co.uk"). + location: City-level geo-targeting. + safe: Safe search ("off", "medium", "high"). + device: Accepted and echoed as ``search_metadata.requested_device`` + (default "desktop"). It does not change Light results. + lr: Language restrict (e.g. "lang_en"). + tbs: Time filter (e.g. "qdr:d" for past 24h). + uule: UULE encoded location. + filter: Show omitted results when set to 0. + nfpr: Set to 1 to disable auto-correction. + cr: Country restrict. + ludocid: Not available on Light (422); use :meth:`search`. + lsig: Not available on Light (422); use :meth:`search`. + kgmid: Not available on Light (422); use :meth:`search`. + si: Cached search params token. + ibp: Not available on Light (422); use :meth:`search`. + uds: Not available on Light (422); use :meth:`search`. google_domain: Alias for domain; Google requests use google.com with country targeting. lat: Latitude; supply together with lon instead of location or uule. lon: Longitude; supply together with lat. radius: Accuracy in meters; needs lat/lon or a city with a known center. color_scheme: Google color scheme. - tbm: Search type; use output=html or the dedicated vertical APIs. - udm: Google result filter: 14 web, 18 forums. Other verticals require output=html. + tbm: Not available on Light (422): Light is web results only. Use + :meth:`search` or the dedicated vertical APIs. + udm: ``"14"`` or ``"web"`` only; any other value gets a 422. no_cache: No effect: ScrapeBadger no longer caches responses, so every call is a fresh Google fetch. Kept for compatibility. as_dt: Site restriction mode: i includes, e excludes as_sitesearch. @@ -669,38 +696,51 @@ async def light( oq: Original query sent to Google. Defaults to q; an empty string omits it. sourceid: Google source identifier. Defaults to chrome; an empty string omits it. ie: Google input encoding hint. Defaults to UTF-8; an empty string omits it. - user_agent: Custom User-Agent override. - output: json returns structured results; html returns the raw page. - q: Search query (supports Google operators like `site:`). - gl: Country code (default "us"). - hl: Language code (default "en"). - num: Results per page (1-100). - start: Page offset (0, 10, 20, ...). - domain: Google domain (e.g. "google.com", "google.co.uk"). - location: City-level geo-targeting. - safe: Safe search ("off", "medium", "high"). - device: "desktop" or "mobile" (server default: desktop). - lr: Language restrict (e.g. "lang_en"). - tbs: Time filter (e.g. "qdr:d" for past 24h). - uule: UULE encoded location. - filter: Show omitted results when set to 0. - nfpr: Set to 1 to disable auto-correction. - cr: Country restrict. - ludocid: Google Place CID. - lsig: Knowledge Graph map ID. - kgmid: Knowledge Graph entity ID. - si: Cached search params token. - ibp: Layout control. - uds: Google filter string. + user_agent: Accepted; ``search_metadata.custom_user_agent`` tells + whether it was sent. It does not change Light results. + output: ``"json"`` (default) returns the response below; + ``"html"`` returns Google's results page HTML as a string. Returns: - ``{search_information, organic_results, related_searches, - pagination}`` — no ``ai_overview`` / ``knowledge_graph`` / - ``ads`` / ``local_results`` / ``news_results`` blocks. - ``search_information.organic_results_state`` is filled, as on - 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. + A dict. Fields without a value are left out, so there are no + ``None`` values: + + - ``search_parameters``: ``gl_requested``, ``domain_requested`` + and ``google_parameters``, the Google parameters the query was + sent with (always ``q``, ``gl``, ``hl`` and ``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``, + ``custom_user_agent``, ``serp_quality`` (``"ok"``) and + ``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`` and ``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. + + With ``output="html"``, a string instead. + + Raises: + ValidationError: 422 for ``tbm``, a ``udm`` other than ``"14"`` + or ``"web"``, ``ludocid``, ``lsig``, ``kgmid``, ``ibp`` or + ``uds``. Light is web results only; use :meth:`search`. + ServerError: 503 with ``Retry-After: 1`` when the results could + not be fetched this time. It is not billed. The SDK retries + it first, like other 5xx. + + Example: + ```python + serp = await client.google.search.light("vinted scraper api", num=20) + for result in serp["organic_results"]: + print(result["position"], result["title"], result["link"]) + ``` """ params: dict[str, Any] = { "google_domain": google_domain, @@ -759,12 +799,13 @@ async def resolve(self, results: list[dict[str, Any]]) -> dict[str, Any]: 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 + A result from :meth:`search` 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. + for you. :meth:`light` results already have their own URL in + ``link`` and need no resolving. Args: results: 1 to 25 rows. Each row needs a non-empty string diff --git a/tests/test_google_targeting.py b/tests/test_google_targeting.py index aa8f5d7..524218d 100644 --- a/tests/test_google_targeting.py +++ b/tests/test_google_targeting.py @@ -48,6 +48,129 @@ async def test_search_raw_html_is_not_lost(method, path): assert result == "café" +LIGHT = "https://example.test/v1/google/light/search" + +# A Light answer in the condensed shape: fields without a value are left out. +LIGHT_ANSWER = { + "search_parameters": { + "gl_requested": "us", + "domain_requested": "google.com", + "google_parameters": {"q": "vinted scraper api", "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": "vinted scraper api", + "url": "https://www.google.com/search?q=vinted+scraper+api&gl=us&hl=en&num=10", + }, + "organic_results": [ + { + "position": 1, + "title": "Vinted API", + "link": "https://example.org/vinted-api", + "displayed_link": "https://example.org \u203a vinted-api", + "snippet": "Search Vinted listings as JSON.", + "rank": 1, + "page_rank": 1, + }, + # displayed_link and snippet can be missing on a result. + { + "position": 2, + "title": "Example", + "link": "https://example.com/", + "rank": 2, + "page_rank": 2, + }, + ], + "pagination": {"current": "1"}, +} + +# What light() sends with only q: its defaults, and nothing that is None. +LIGHT_DEFAULTS = { + "q": "vinted scraper api", + "gl": "us", + "hl": "en", + "num": "10", + "start": "0", + "domain": "google.com", + "safe": "off", + "no_cache": "false", +} + + +@respx.mock +async def test_light_calls_light_endpoint_with_its_defaults(): + route = respx.get(LIGHT).mock(return_value=httpx.Response(200, json=LIGHT_ANSWER)) + async with ScrapeBadger(api_key="test", base_url="https://example.test") as client: + result = await client.google.search.light("vinted scraper api") + assert result == LIGHT_ANSWER + assert route.call_count == 1 + assert dict(route.calls.last.request.url.params) == {**LIGHT_DEFAULTS, "output": "json"} + + +@respx.mock +async def test_light_sends_the_light_parameters(): + route = respx.get(LIGHT).mock(return_value=httpx.Response(200, json=LIGHT_ANSWER)) + async with ScrapeBadger(api_key="test", base_url="https://example.test") as client: + await client.google.search.light( + "site:vinted.com scraper", + gl="de", + hl="de", + num=30, + start=10, + location="Berlin, Germany", + safe="active", + device="mobile", + lr="lang_de", + tbs="qdr:w", + filter=0, + nfpr=1, + cr="countryDE", + udm="14", + as_sitesearch="vinted.de", + user_agent="my-agent", + ) + sent = dict(route.calls.last.request.url.params) + assert route.calls.last.request.url.path == "/v1/google/light/search" + assert sent == { + "q": "site:vinted.com scraper", + "gl": "de", + "hl": "de", + "num": "30", + "start": "10", + "domain": "google.com", + "location": "Berlin, Germany", + "safe": "active", + "device": "mobile", + "lr": "lang_de", + "tbs": "qdr:w", + "filter": "0", + "nfpr": "1", + "cr": "countryDE", + "udm": "14", + "as_sitesearch": "vinted.de", + "user_agent": "my-agent", + "no_cache": "false", + "output": "json", + } + # Light has none of full Search's controls. + assert not {"mode", "ai_overview", "expand_related_questions"} & sent.keys() + + +@respx.mock +async def test_light_html_sends_the_same_parameters(): + page = httpx.Response(200, text="", headers={"content-type": "text/html"}) + route = respx.get(LIGHT).mock(return_value=page) + async with ScrapeBadger(api_key="test", base_url="https://example.test") as client: + await client.google.search.light("vinted scraper api", output="html") + # Parameters left as None are not sent as empty values. + assert dict(route.calls.last.request.url.params) == {**LIGHT_DEFAULTS, "output": "html"} + + @pytest.mark.parametrize("body", [{"detail": "Conflicting targeting"}, "invalid targeting"]) @respx.mock async def test_raw_html_still_raises_api_errors(body): diff --git a/uv.lock b/uv.lock index 29bff5b..1d42432 100644 --- a/uv.lock +++ b/uv.lock @@ -930,7 +930,7 @@ wheels = [ [[package]] name = "scrapebadger" -version = "0.88.0" +version = "0.89.0" source = { editable = "." } dependencies = [ { name = "httpx" }, From 0854de1a1795e3c783b1029bdd7ac96d2a5b82f3 Mon Sep 17 00:00:00 2001 From: kasparasizi1 <132673909+kasparasizi1@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:31:29 +0200 Subject: [PATCH 2/2] refactor(client): filter get_raw params without a branch The `if params:` guard left a branch no caller takes (both callers pass params), which codecov/patch counted as a partial line. Co-Authored-By: Claude Opus 5.5 --- src/scrapebadger/_internal/client.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/scrapebadger/_internal/client.py b/src/scrapebadger/_internal/client.py index ac140b4..fdea041 100644 --- a/src/scrapebadger/_internal/client.py +++ b/src/scrapebadger/_internal/client.py @@ -543,9 +543,8 @@ async def get_raw( ScrapeBadgerError: For API errors. """ # Leave out None values, as _request does; httpx would send them as empty strings. - if params: - params = {k: v for k, v in params.items() if v is not None} - response = await self._execute_request("GET", path, params=params) + sent = {k: v for k, v in (params or {}).items() if v is not None} + response = await self._execute_request("GET", path, params=sent) if response.status_code >= 400: try: