Skip to main content

serpwright

CI PyPI Python

Scrape organic Google search results from the command line or from Python.

For each result you get:

Field Example
link https://www.google.com/goto?url=CAES… (the real URL with --resolve)
title Playwright Python Get Started
description Learn Playwright with our tutorial. In this chapter you install…
website_name W3Schools
favicon_url https://www.google.com/s2/favicons?sz=64&domain=www.w3schools.com

Google only serves results to browsers that run JavaScript, so serpwright drives a real Chromium through Patchright, a Playwright fork patched to look less like automation.

By default link is Google's own redirect link (google.com/goto?url=…). Opening it redirects to the result, even outside serpwright's browser (no cookies needed). Pass --resolve to get the real URLs instead; it's much slower, because Google rate-limits the lookups.

Requirements

  • Python 3.11 or later
  • Linux
  • Xvfb, to run without a visible window: sudo apt install xvfb

Installation

serpwright drives Chromium, so after installing the package, download the browser once with patchright install chromium --no-shell.

With uv

# As a tool, available everywhere, from PyPI:
uv tool install --with-executables-from patchright serpwright
patchright install chromium --no-shell

# Or from a clone (runs from the project's own virtual environment):
git clone https://github.com/AntoinePaix/serpwright.git && cd serpwright
uv sync
uv run patchright install chromium --no-shell

--with-executables-from patchright also puts the patchright command on your PATH, which the second line needs to download the browser.

With pip

pip install serpwright
patchright install chromium --no-shell

Usage

serpwright "best python web frameworks"                      # 1 page, JSON to stdout
serpwright "best python web frameworks" --pages 2 -o results.json
serpwright "site:github.com playwright" -n 25 -f csv -o out.csv
serpwright "rust async" --period week --country us --fields link,title
serpwright "recette crêpes" -l fr -c fr --only-lang fr       # French pages only
serpwright "query" --headful                                 # visible window

From a source checkout without installing, prefix the commands with uv run (for example uv run serpwright "query"), or use uv run python -m serpwright "query".

Options

Results

Option Description
-p, --pages N Result pages to fetch, about 10 results each (default: 1)
-n, --max-results N Fetch pages until N results are collected (cannot be combined with --pages)

Language and country

Google has two kinds of settings. --lang and --country only bias the results: pages in other languages or from other countries still show up. --only-lang and --only-country filter them, so only matching pages are returned. Combine both for fully localised results.

Option Description
-l, --lang CODE Interface language, Google's hl parameter, e.g. en, fr, pt-BR (default: en)
-c, --country CODE Search as if from this country, Google's gl parameter, e.g. us, fr
-L, --only-lang CODES Only pages in these languages, Google's lr parameter, e.g. fr or fr,en
-C, --only-country CODES Only pages from these countries, Google's cr parameter, e.g. fr or fr,be,ch
--list-languages List the languages --only-lang accepts (Google supports about 35)

Countries use two-letter ISO codes; gb is accepted for the United Kingdom. The browser's language (its Accept-Language header) is set from --lang and --country, for example fr-CA, so it matches the search settings.

Example: the query python playwright tutorial with -l de -c de still returns mostly English pages, while adding -L de -C de returns only German pages from German sites.

Filters

Option Description
--period {hour,day,week,month,year} Only results from that recent period
--safe Turn on SafeSearch
--param KEY=VALUE Add any other Google URL parameter (repeatable), e.g. --param filter=0

Output

Option Description
-f, --format {json,jsonl,csv} Output format (default: json)
-o, --output FILE Write to a file instead of stdout
--fields LIST Comma-separated fields to keep, e.g. link,title
--resolve Resolve Google's google.com/goto?... redirect links to the real URLs (slow; off by default)
-q, --quiet Only print errors
-v, --verbose Log progress; -vv for debug output

Browser

There are three display modes. The default runs a normal browser on an invisible Xvfb display: no window appears, and Google treats it like a real browser.

Option Description
--headful Show the browser window, so you can solve a CAPTCHA by hand
--headless Use Chromium's real headless mode. Doesn't need Xvfb, but Google often answers with a CAPTCHA, especially with a fresh profile
--chrome Use your installed Google Chrome instead of the bundled Chromium
--profile-dir DIR Browser profile that keeps cookies between runs (default: ~/.cache/serpwright-profile)
--no-profile Use a throwaway profile

Timing

Option Description
--delay MIN MAX Random pause between pages, in seconds (default: 2 5)
--timeout SECONDS Page load timeout (default: 30)
--resolve-retries N With --resolve: rate-limit pages to wait through for each redirect link (default: 4)
--resolve-concurrency N With --resolve: redirect links to resolve in parallel (default: 1)
--resolve-max-wait SECONDS With --resolve: longest rate-limit wait to sit through; past it, the remaining links of the run stay redirect links (default: 15)
--captcha-wait SECONDS Time allowed to solve a CAPTCHA with --headful (default: 180)

Exit codes

Code Meaning
0 Results found
1 No results
2 Invalid command-line arguments
3 Google returned a CAPTCHA
130 Interrupted (Ctrl+C)

Python API

search() is a coroutine:

import asyncio

from serpwright import SearchOptions, search


async def main():
    results = await search(
        "python playwright tutorial",
        SearchOptions(max_results=20, lang="fr", country="fr", only_languages=["fr"]),
    )
    for r in results:
        print(r.website_name, r.link)


asyncio.run(main())

Without an event loop, use the blocking wrapper search_sync(), which takes the same arguments:

from serpwright import search_sync

results = search_sync("python playwright tutorial")

SearchOptions has one field for each command-line option. See src/serpwright/scraper.py.

Each search() call starts its own browser. To run several searches at the same time (for example with asyncio.gather), give each one its own profile folder, or profile=None for a throwaway profile: Chromium can't open the same profile twice. Keep the number of parallel searches small, since Google is quicker to show CAPTCHAs to bursts of traffic.

With resolve_links=True (--resolve), resolve_concurrency (--resolve-concurrency) resolves redirect links in parallel. In one test, 4 cut a 10-result run from 38 s to 22 s, but left 2 links unresolved instead of 1.

How it works

  • No visible window, but not headless. Google answers Chromium's headless mode with a CAPTCHA, even under Patchright. By default serpwright starts its own Xvfb virtual display and runs a normal browser on it, so nothing appears on screen. Without Xvfb it falls back to real headless mode and prints a warning. --headless picks real headless mode directly.
  • Cookie consent. In the EU, Google first shows a consent page. serpwright clicks "Accept all" and keeps the cookie in its browser profile.
  • Parsing. Results are found by their structure (a link that contains an <h3> heading), not by Google's obfuscated class names, which change often. "People also ask" boxes and carousels are skipped.
  • Real links (--resolve). Google now wraps result links in redirects (google.com/goto?url=<token>) and leaves the destination out of the page. With --resolve, serpwright asks Google for each redirect's destination without following it. After a few lookups Google shows a "Validating your request…" page. serpwright waits as long as that page says, then continues. The wait grows the more links are looked up from the same IP address (from 3 s to nearly a minute in testing), so once Google asks for more than --resolve-max-wait seconds, serpwright stops resolving for the rest of the run instead of retrying early. Each link is looked up only once per run. The token in these links is encrypted by Google, so it can't be decoded locally.
  • Website name and favicon without resolving. Both come from the page itself: the site name Google shows, and the domain of the URL Google displays under the title. They are filled in even when link is a redirect.
  • Favicons. Google embeds favicons in the page as inline image data, so favicon_url is built from the result's domain using Google's public favicon service.

Limitations

  • --resolve is slow: about 20–40 seconds per page, mostly spent waiting on Google's rate limit for redirect links. Without it, a page takes a few seconds.
  • With --resolve, a few links per page can stay unresolved. They keep their google.com/goto link.
  • Google can still show a CAPTCHA at higher volume or from flagged IP addresses. Run once with --headful and solve it; the cookie is saved in the profile for later runs.
  • Google changes its result page often, so parsing can break without warning.
  • Your IP address's location still affects results, even with --country. Use --only-lang and --only-country when the results must match.

Development

serpwright uses the same tooling as the other scraper repos: uv, ruff, pytest, pre-commit and the same GitHub Actions pipeline.

uv sync                                         # project + dev tools (pytest, ruff, pre-commit)
uv run patchright install chromium --no-shell   # for the browser tests
uv run pre-commit install                       # once: run the hooks on every commit

uv run pytest                       # offline tests
uv run pytest -m live               # smoke test against the real google.com
uv run ruff check --fix . && uv run ruff format .
uv run pre-commit run --all-files   # every hook, as the CI does

Without uv: pip install -e . --group dev (--group needs pip 25.1+), then run the same commands without the uv run prefix.

  • Tests: the offline tests never contact Google. Most replace the browser with fakes; the parsing tests load a hand-written results page (tests/fixtures/serp.html) in a local Chromium and are skipped if Chromium isn't installed. The virtual-display test is skipped without Xvfb.
  • Pre-commit hooks: they block .env files, .har captures and token.json files, scan for secrets with gitleaks, refuse files over 1 MB, check YAML and TOML files, fix trailing whitespace and final newlines, run ruff check --fix and ruff format, and keep uv.lock in sync with pyproject.toml.
  • CI (.github/workflows/ci.yml): on every push to main and every pull request, one job runs all the pre-commit hooks, and another installs Chromium and Xvfb and runs the offline tests on Python 3.11, 3.12, 3.13 and 3.14.
  • Code style: ruff with 120-character lines, one import per line and absolute imports only (see pyproject.toml).
  • Releases (.github/workflows/release.yml): pushing a version tag such as v0.1.0 checks it matches the version in pyproject.toml, runs the tests, builds the package, publishes it to PyPI and creates a GitHub release with the wheel, the sdist and the list of commits since the previous tag.

Releasing

Versions follow MAJOR.MINOR.PATCH: bump minor for new features or breaking changes (while the version is 0.x), patch for fixes only.

uv version --bump minor                          # e.g. 0.1.0 -> 0.2.0, in pyproject.toml and uv.lock
git commit -am "Release 0.2.0"
git tag v0.2.0
git push origin main v0.2.0                       # the release workflow publishes to PyPI and GitHub

Release candidates test the whole chain on PyPI first: pip only installs them when asked explicitly (pip install serpwright==0.2.0rc1), and they are marked as pre-releases on GitHub.

uv version 0.2.0rc1                               # then commit, tag v0.2.0rc1 and push as above

The package is named serpwright because gscraper is taken on PyPI by another project.

PyPI publishing uses Trusted Publishing: no token is stored, PyPI trusts the release workflow itself. It is configured once on pypi.org, in the project's Settings > Publishing (or Your account > Publishing > Add a new pending publisher before the first upload), GitHub tab:

Field Value
PyPI Project Name serpwright
Owner AntoinePaix
Repository name serpwright
Workflow name release.yml
Environment name pypi

Repository layout

.github/workflows/ci.yml        lint (pre-commit) + tests on Python 3.11 to 3.14
.github/workflows/release.yml   PyPI + GitHub release on a version tag (v*)
src/serpwright/
├── cli.py          # command line (argparse), JSON/JSONL/CSV output written with aiofiles
├── scraper.py      # browser (Patchright + Xvfb), result parsing, redirect resolution
├── locales.py      # language and country codes (hl, gl, lr, cr)
└── py.typed        # the package ships type hints
tests/              # pytest suite, hand-written results page, live smoke test

Disclaimer

Scraping Google is against its Terms of Service. Keep the volume low, keep the delays, and use an official or commercial search API for anything at scale. You are responsible for how you use this tool.

License

MIT

Metadata

Release files for serpwright 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for serpwright 0.1.0
File Size Uploaded Provenance Actions
serpwright-0.1.0.tar.gz 21.2 kB Without provenance Details for serpwright-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for serpwright 0.1.0
File Interpreter ABI Platform Actions
serpwright-0.1.0-py3-none-any.whl Python 3 none any Details for serpwright-0.1.0-py3-none-any.whl

Total release size: 43.8 kB

Release files / serpwright-0.1.0.tar.gz

Download URL serpwright-0.1.0.tar.gz
Size 21.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8a34e071086211da88c0954649a29b44a5cf62b4999d1db2df4f4b583ff6431c
BLAKE2b-256 checksum
How to use checksums
5710b442beb51dd79ba1698f2e6629ef87d890d063d2a1587d79442d51597c09
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / serpwright-0.1.0-py3-none-any.whl

Download URL serpwright-0.1.0-py3-none-any.whl
Size 22.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
887ae425d2f6708dad075b2a336fb930af186c1e769ff8ef66f97819fda7e6e6
BLAKE2b-256 checksum
How to use checksums
c34eac2e9cbc642283b342141e1073abf9ae1d6a6ea774b25a11c06c7446ffea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for serpwright 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page