Metadata-Version: 2.4
Name: serpwright
Version: 0.1.0rc1
Summary: Scrape Google search results (link, title, description, site name, favicon) with a stealth browser.
Keywords: google,serp,search,scraper,patchright,playwright
Author: Antoine Paix
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
Classifier: Typing :: Typed
Requires-Dist: aiofiles>=25.1
Requires-Dist: patchright>=1.64.1
Requires-Python: >=3.11
Project-URL: Homepage, https://github.com/AntoinePaix/serpwright
Project-URL: Issues, https://github.com/AntoinePaix/serpwright/issues
Description-Content-Type: text/markdown

# serpwright

[![CI](https://github.com/AntoinePaix/serpwright/actions/workflows/ci.yml/badge.svg)](https://github.com/AntoinePaix/serpwright/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/serpwright)](https://pypi.org/project/serpwright/)
[![Python](https://img.shields.io/pypi/pyversions/serpwright)](https://pypi.org/project/serpwright/)

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](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright-python),
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

```bash
# 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

```bash
pip install serpwright
patchright install chromium --no-shell
```

## Usage

```bash
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) |
| `--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:

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

```python
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`](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.
- **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](https://docs.astral.sh/uv/), [ruff](https://docs.astral.sh/ruff/),
[pytest](https://docs.pytest.org/), [pre-commit](https://pre-commit.com/) and
the same GitHub Actions pipeline.

```bash
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](https://pypi.org/project/serpwright/)
  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.

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

```bash
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](https://docs.pypi.org/trusted-publishers/):
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](https://policies.google.com/terms).
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](LICENSE)
