From 901537ba887b55ef9b4b26a632e98b74a28ab6d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 16:51:00 +0200 Subject: [PATCH 01/21] Add Session.classify for the browser's classify tool Regenerated from a browser built from its page-classify branch. Like extract's schema, classify's questions is a JSON string on the wire, so the generator now types both as `str | dict | list` from one table. The tests answer through a mock TypeSafe server (TYPESAFE_BASE_URL) and skip on a binary without the tool, such as the nightly CI builds against until classify ships. --- lightpanda/_methods.py | 16 ++++++++ scripts/generate_methods.py | 5 ++- tests/test_classify.py | 75 +++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 tests/test_classify.py diff --git a/lightpanda/_methods.py b/lightpanda/_methods.py index 85229d3..a2218f9 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -20,6 +20,14 @@ class SessionMethods: def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError + def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + + Args: + questions: JSON string: array of categories, or object of questions + selector: Optional CSS selector to classify a specific element subtree instead of the full page + """ + return self.call("classify", questions=questions, selector=selector) def click(self, *, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Click on an interactive element. Provide either a CSS selector (preferred for reproducibility) or a backendNodeId. Returns the current page URL and title after the click. @@ -472,6 +480,14 @@ class AsyncSessionMethods: async def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError + async def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + + Args: + questions: JSON string: array of categories, or object of questions + selector: Optional CSS selector to classify a specific element subtree instead of the full page + """ + return await self.call("classify", questions=questions, selector=selector) async def click(self, *, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Click on an interactive element. Provide either a CSS selector (preferred for reproducibility) or a backendNodeId. Returns the current page URL and title after the click. diff --git a/scripts/generate_methods.py b/scripts/generate_methods.py index 81a584e..9d553cd 100644 --- a/scripts/generate_methods.py +++ b/scripts/generate_methods.py @@ -37,6 +37,9 @@ PY_TYPES = {"string": "str", "integer": "int", "number": "float", "boolean": "bool", "object": "dict", "array": "list"} +# String params that carry JSON, which `Session.call` serializes from a dict or list. +JSON_STRING_PARAMS = {("extract", "schema"), ("classify", "questions")} + HEADER = '''\ """Generated by scripts/generate_methods.py — do not edit. @@ -116,7 +119,7 @@ def method_source(name: str, spec: dict, is_async: bool = False, on_element: boo for prop in sorted(properties, key=lambda p: p not in required): arg = args[prop] py_type = PY_TYPES.get(properties[prop].get("type", ""), "Any") - if name == "extract" and prop == "schema": + if (name, prop) in JSON_STRING_PARAMS: py_type = "str | dict | list" if prop in required: params.append(f"{arg}: {py_type}") diff --git a/tests/test_classify.py b/tests/test_classify.py new file mode 100644 index 0000000..a1f2f02 --- /dev/null +++ b/tests/test_classify.py @@ -0,0 +1,75 @@ +import http.server +import json +import threading + +import pytest + +from lightpanda import Browser + + +class MockTypeSafe(http.server.BaseHTTPRequestHandler): + """Answers every question asked: 0.9 for a noul, the first option for a choice.""" + + def do_POST(self): + request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + answers = {} + for key, question in request["questions"].items(): + if question["type"] == "noul": + answers[key] = {"type": "noul", "noul": 0.9} + else: + options = list(question["criteria"]) + rest = 0.2 / max(len(options) - 1, 1) + answers[key] = { + "type": "choice", + "choice": options[0], + "probabilities": {o: 0.8 if i == 0 else rest for i, o in enumerate(options)}, + "confidence": 0.8, + } + body = json.dumps({"model": "jev-1.13.0", "answers": answers}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +@pytest.fixture(scope="module") +def typesafe_url(): + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), MockTypeSafe) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{server.server_address[1]}" + server.shutdown() + + +@pytest.fixture(scope="module") +def classify_browser(binary, typesafe_url): + env = {"TYPESAFE_API_KEY": "test-key", "TYPESAFE_BASE_URL": typesafe_url} + with Browser(binary=binary, env=env) as b: + if "classify" not in b.tools: + pytest.skip("binary has no classify tool") + yield b + + +def test_classify_categories(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/index.html") + assert page.classify(questions=["home", "article"]) == "home" + + +def test_classify_presets_and_questions(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/index.html") + result = page.classify( + questions={ + "isBlocked": True, + "has_list": "Does the page show a list of links?", + "kind": {"question": "What kind of page?", "options": ["home", "article"]}, + }, + selector="body", + ) + assert result["isBlocked"] == 0.9 + assert result["has_list"] == 0.9 + assert result["kind"]["choice"] == "home" From 0df6b7cca43c766c3d9190a4fef1b755c647e41c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 21:06:14 +0200 Subject: [PATCH 02/21] Add Session.judge: every classify preset as a PageVerdict judge() asks the browser for all its presets in one classify call, through the empty questions object, and answers with bools at a threshold: is_blocked, is_login_wall, is_paywall and the rest, plus `ok` when none fired and `reason` for the strongest that did. `scores` keeps the probabilities, since Jev is not deterministic and a borderline score can land either side. More than one can be true at once (a consent banner on a login wall, a bot block that is also an error page), so the verdict is a set of flags rather than one class. The browser owns the preset list: one added later still shows up in `scores` and as an attribute without a release here. Regenerated from a browser built from its page-classify branch. --- lightpanda/__init__.py | 3 +- lightpanda/_methods.py | 8 ++-- lightpanda/async_browser.py | 6 ++- lightpanda/browser.py | 82 +++++++++++++++++++++++++++++++++++++ tests/test_classify.py | 21 ++++++++++ 5 files changed, 114 insertions(+), 6 deletions(-) diff --git a/lightpanda/__init__.py b/lightpanda/__init__.py index 9e89541..2cea5a6 100644 --- a/lightpanda/__init__.py +++ b/lightpanda/__init__.py @@ -38,7 +38,7 @@ from .async_browser import AsyncBrowser, AsyncElement, AsyncSession, run_script_async from .webdriver import AsyncWebDriverServer, WebDriverServer -from .browser import Browser, Element, PageResult, Session, run_script +from .browser import Browser, Element, PageResult, PageVerdict, Session, run_script from .cdp import AsyncCDPServer, CDPServer from .errors import LightpandaError, ProcessError, ProtocolError, ScriptError, ToolError @@ -47,6 +47,7 @@ "Session", "Element", "PageResult", + "PageVerdict", "run_script", "AsyncBrowser", "AsyncSession", diff --git a/lightpanda/_methods.py b/lightpanda/_methods.py index a2218f9..fb827a5 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -21,10 +21,10 @@ def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: - """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. Args: - questions: JSON string: array of categories, or object of questions + questions: JSON string: array of categories, or object of questions (`{}` for every preset) selector: Optional CSS selector to classify a specific element subtree instead of the full page """ return self.call("classify", questions=questions, selector=selector) @@ -481,10 +481,10 @@ async def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError async def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: - """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. Args: - questions: JSON string: array of categories, or object of questions + questions: JSON string: array of categories, or object of questions (`{}` for every preset) selector: Optional CSS selector to classify a specific element subtree instead of the full page """ return await self.call("classify", questions=questions, selector=selector) diff --git a/lightpanda/async_browser.py b/lightpanda/async_browser.py index b1eb5cd..0d74469 100644 --- a/lightpanda/async_browser.py +++ b/lightpanda/async_browser.py @@ -17,7 +17,7 @@ from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor -from .browser import Browser, Element, Session, _generated, run_script +from .browser import Browser, Element, PageVerdict, Session, _generated, run_script from .client import _documented from .errors import LightpandaError @@ -58,6 +58,10 @@ async def call(self, tool: str, **kwargs): return [AsyncElement(node, self) if isinstance(node, Element) else node for node in result] return result + async def judge(self, *, threshold: float = 0.5) -> PageVerdict: + """Judge whether the page is worth reading; see :meth:`Session.judge`.""" + return await _run(self._executor, self._session.judge, threshold=threshold) + def __getattr__(self, attr: str): session = self.__dict__.get("_session") if session is not None and session._resolve(attr): diff --git a/lightpanda/browser.py b/lightpanda/browser.py index 37c895b..1bb9c99 100644 --- a/lightpanda/browser.py +++ b/lightpanda/browser.py @@ -58,6 +58,76 @@ def __new__(cls, text: str, page_state: dict): return self +class PageVerdict: + """What :meth:`Session.judge` found: is this page worth reading? + + Every preset of the ``classify`` tool, asked in one call. Each is a bool, + true when the model's probability reaches the threshold; ``scores`` keeps + the probabilities themselves (None where the model gave no answer). The + browser decides which presets there are: one added after this release + still appears in ``scores`` and as an attribute. + + More than one can be true: a cookie banner can sit on top of a login wall, + and a bot block is usually an error page too. :attr:`reason` names the + strongest one. + + The model is not deterministic, so the same page can score a little + differently from one call to the next, and a score near the threshold can + land on either side of it. + + ```python + verdict = page.judge() + if not verdict.ok: + print("skipping:", verdict.reason) # is_paywall + verdict.scores["is_blocked"] # 0.03 + ``` + """ + + is_blocked: bool + """The page is behind a CAPTCHA, a Cloudflare challenge or a bot block.""" + is_captcha: bool + """A CAPTCHA or human verification challenge covers the content.""" + is_consent_wall: bool + """A cookie consent banner covers the content.""" + is_empty_catalog: bool + """The page says no matching products were found.""" + is_error_page: bool + """An error, such as page not found, stands in for the content.""" + is_login_wall: bool + """A sign-in form or prompt stands in for the content.""" + is_paywall: bool + """A subscription or payment prompt hides or cuts off the content.""" + is_unsupported_browser: bool + """The site says this browser is unsupported, or that JavaScript must be + enabled: its scripts failed or rejected Lightpanda.""" + is_loading: bool + """The page says it is still loading (spinners, placeholders, loading + text). A page that is blank while it loads says nothing, so this misses it.""" + scores: dict[str, float | None] + """Each check's probability, keyed by its attribute name.""" + + def __init__(self, answers: dict, threshold: float): + self.scores = {_snake(preset): score for preset, score in answers.items()} + for attr, score in self.scores.items(): + setattr(self, attr, score is not None and score >= threshold) + + @property + def ok(self) -> bool: + """True when no check fired.""" + return not any(getattr(self, attr) for attr in self.scores) + + @property + def reason(self) -> str | None: + """The check that fired with the highest score, e.g. ``"is_paywall"``, + to answer "why skip this page?" in one word. None when :attr:`ok`.""" + fired = [attr for attr in self.scores if getattr(self, attr)] + return max(fired, key=self.scores.__getitem__, default=None) + + def __repr__(self) -> str: + fired = ", ".join(f"{attr}={self.scores[attr]}" for attr in self.scores if getattr(self, attr)) + return f"PageVerdict({fired})" + + def _snake(name: str) -> str: return re.sub(r"(? PageVerdict: + """Judge whether the page is worth reading: blocked, a login wall, a + paywall, an error page and the rest of the ``classify`` presets, in a + single call. + + Args: + threshold: The probability at which a check counts as true. + """ + # An empty questions object asks the browser for every preset. + answers = self.call("classify", questions={}) + return PageVerdict(answers, threshold) + def _resolve(self, attr: str) -> str | None: """The tool name behind a snake_case public attribute, if any.""" name = self._snake_map.get(attr) diff --git a/tests/test_classify.py b/tests/test_classify.py index a1f2f02..78872d5 100644 --- a/tests/test_classify.py +++ b/tests/test_classify.py @@ -73,3 +73,24 @@ def test_classify_presets_and_questions(classify_browser, fixture_url): assert result["isBlocked"] == 0.9 assert result["has_list"] == 0.9 assert result["kind"]["choice"] == "home" + + + +def test_judge(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/index.html") + verdict = page.judge() + assert verdict.is_blocked and verdict.is_paywall and not verdict.ok + assert set(verdict.scores) >= {"is_blocked", "is_login_wall", "is_unsupported_browser"} + assert set(verdict.scores.values()) == {0.9} + assert verdict.reason in verdict.scores + assert page.judge(threshold=0.95).ok + assert page.judge(threshold=0.95).reason is None + + +async def test_judge_async(classify_browser, fixture_url): + from lightpanda import AsyncBrowser + + async with AsyncBrowser.wrap(classify_browser).session() as page: + await page.goto(url=f"{fixture_url}/index.html") + assert (await page.judge()).is_captcha From d5130b54c45f3aa77b50ad943d1aae8081858e9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 21:06:14 +0200 Subject: [PATCH 03/21] Add a classify example that triages a crawl classify_pages.py asks each page what it is (presets, a yes/no question, a choice, a category list scoped by selector), then gates the same URLs with judge(). Until a release ships judge(), its inline metadata installs this checkout rather than the PyPI package. --- examples/README.md | 59 +++++++++++++++++++++++ examples/classify_pages.py | 97 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 examples/classify_pages.py diff --git a/examples/README.md b/examples/README.md index 9b37986..6e9e9ad 100644 --- a/examples/README.md +++ b/examples/README.md @@ -7,6 +7,7 @@ anywhere with [uv](https://docs.astral.sh/uv/) and nothing pre-installed: uv run examples/quotes_analysis.py uv run examples/compare.py --repeat 5 uv run examples/neurips_topics.py +uv run examples/classify_pages.py # needs TYPESAFE_API_KEY ``` Set `LIGHTPANDA_BIN=/path/to/lightpanda` to run against a local browser build @@ -214,3 +215,61 @@ scores the same as `-2` within noise, but it is the legacy model. With a key the whole corpus embeds in about twenty seconds; without one it takes considerably longer, once, and the 27 MB cache under `~/.cache/neurips_topics` makes every later run instant. + +## `classify_pages.py` — triage a crawl before scraping it + +A 200 response can still be a consent wall, a bot check or an empty search. +`classify` asks TypeSafe's page model about the rendered page, so a single +call per URL tells you whether the page is worth extracting from and what +kind of page it is. One `questions` dict can mix presets, yes/no questions +and a choice: + +```python +answers = page.classify(questions={ + "isBlocked": True, "isConsentWall": True, "isEmptyCatalog": True, # presets + "has_price": "Does the page show a price?", # yes/no -> probability + "kind": {"question": "What kind of page is this?", + "options": ["homepage", "listing", "product", "article", "search results", "login"]}, +}) +page.classify(questions=["software", "biology", "history"], selector="#bodyContent") # -> "software" +``` + +When all you need is the gate, `page.judge()` asks every preset in one call +and answers with bools, keeping the probabilities in `scores`: + +```python +verdict = page.judge() +if not verdict.ok: + print("skip", verdict.reason) # is_blocked +``` + +``` +page kind price flags +quotes.toscrape.com/js/ homepage 0.01 - +books.toscrape.com/catalogue/a-light-in-the- product 1.00 - +en.wikipedia.org/wiki/Headless_browser article 0.02 - +news.ycombinator.com/login login 0.01 - +en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 isEmptyCatalog 0.55 +www.g2.com/ homepage 0.02 isBlocked 0.77 +www.yahoo.com/ article 0.01 isConsentWall 0.69 + +keep quotes.toscrape.com/js/ +keep books.toscrape.com/catalogue/a-light-in-the- +keep en.wikipedia.org/wiki/Headless_browser +skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.94) +skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.56) +skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.75, is_error_page=0.95) +skip www.yahoo.com/ is_consent_wall PageVerdict(is_consent_wall=0.68) +``` + +The model is not deterministic, so expect the scores to move a little between +runs, and a borderline flag such as the empty search's to come and go. Some +sites change too: Yahoo only sometimes redirects to its consent page. + +Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a +release ships both, the script installs this checkout rather than the PyPI +package, so run it from here against a local browser build: + +```bash +LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages.py +``` diff --git a/examples/classify_pages.py b/examples/classify_pages.py new file mode 100644 index 0000000..e4e223c --- /dev/null +++ b/examples/classify_pages.py @@ -0,0 +1,97 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["lightpanda"] +# +# # judge() is not on PyPI yet: use this checkout until it is. +# [tool.uv.sources] +# lightpanda = { path = "..", editable = true } +# /// +"""Triage a crawl: ask each page what it is before scraping it. + +A scraper that gets HTTP 200 can still be looking at a cookie wall, a bot +check or a search with no results. ``classify`` asks TypeSafe's page model +about the rendered page, so one call per URL says whether the page is worth +extracting from and what kind of page it is: + +- ``True`` asks a preset: isBlocked, isCaptcha, isConsentWall, isEmptyCatalog +- a string asks a yes/no question and returns its probability +- ``{"question", "options"}`` asks a choice +- a plain list of categories returns the one that fits + +When all you need is the gate, ``page.judge()`` asks every preset in one call +and answers with bools: ``ok`` is true when none of them fired. + +Needs TYPESAFE_API_KEY in the environment. + +Run: uv run examples/classify_pages.py +""" + +import os +import sys + +from lightpanda import Browser + +URLS = [ + "https://quotes.toscrape.com/js/", + "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", + "https://en.wikipedia.org/wiki/Headless_browser", + "https://news.ycombinator.com/login", + "https://en.wikipedia.org/w/index.php?search=xqzzzvqk+plorbt&fulltext=1&ns0=1", + "https://www.g2.com/", + "https://www.yahoo.com/", +] + +QUESTIONS = { + "isBlocked": True, + "isCaptcha": True, + "isConsentWall": True, + "isEmptyCatalog": True, + "has_price": "Does the page show a price?", + "kind": { + "question": "What kind of page is this?", + "options": ["homepage", "listing", "product", "article", "search results", "login"], + }, +} + +PRESETS = ["isBlocked", "isCaptcha", "isConsentWall", "isEmptyCatalog"] + + +def main() -> None: + if not os.environ.get("TYPESAFE_API_KEY"): + sys.exit("Set TYPESAFE_API_KEY to use classify.") + + with Browser() as browser: + if "classify" not in browser.tools: + sys.exit("This lightpanda binary has no classify tool; point LIGHTPANDA_BIN at a newer one.") + + print(f"{'page':<44} {'kind':<16} {'price':>5} flags") + for url in URLS: + with browser.new_session() as page: + page.goto(url=url) + answers = page.classify(questions=QUESTIONS) + kind = answers["kind"] + flags = ", ".join(f"{p} {answers[p]:.2f}" for p in PRESETS if answers[p] >= 0.5) + name = url.split("://", 1)[1][:44] + print( + f"{name:<44} {kind['choice']:<16} {answers['has_price']:>5.2f} {flags or '-'}" + ) + + # A list of categories is the shortest form, and `selector` narrows the + # question to one part of the page. + with browser.new_session() as page: + page.goto(url="https://en.wikipedia.org/wiki/Headless_browser") + topic = page.classify(questions=["software", "biology", "history", "sports"], selector="#bodyContent") + print(f"\nWikipedia article body is about: {topic}") + + # judge() is the gate on its own: every preset, as bools. + print() + for url in URLS: + with browser.new_session() as page: + page.goto(url=url) + verdict = page.judge() + name = url.split("://", 1)[1][:44] + print(f"keep {name}" if verdict.ok else f"skip {name:<44} {verdict.reason:<16} {verdict}") + + +if __name__ == "__main__": + main() From e7fd985124eefbae47fce22f6558db9f192a8fed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 22:04:01 +0200 Subject: [PATCH 04/21] Describe is_empty_catalog as any empty search, as the browser now asks The example output is refreshed from a run against that browser: the empty Wikipedia search now scores 0.99 instead of a borderline 0.56. --- examples/README.md | 19 ++++++++++--------- lightpanda/browser.py | 2 +- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/examples/README.md b/examples/README.md index 6e9e9ad..ec18356 100644 --- a/examples/README.md +++ b/examples/README.md @@ -247,24 +247,25 @@ if not verdict.ok: page kind price flags quotes.toscrape.com/js/ homepage 0.01 - books.toscrape.com/catalogue/a-light-in-the- product 1.00 - -en.wikipedia.org/wiki/Headless_browser article 0.02 - +en.wikipedia.org/wiki/Headless_browser article 0.01 - news.ycombinator.com/login login 0.01 - -en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 isEmptyCatalog 0.55 +en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 isEmptyCatalog 0.99 www.g2.com/ homepage 0.02 isBlocked 0.77 -www.yahoo.com/ article 0.01 isConsentWall 0.69 +www.yahoo.com/ article 0.01 isConsentWall 0.70 keep quotes.toscrape.com/js/ keep books.toscrape.com/catalogue/a-light-in-the- keep en.wikipedia.org/wiki/Headless_browser -skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.94) -skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.56) -skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.75, is_error_page=0.95) -skip www.yahoo.com/ is_consent_wall PageVerdict(is_consent_wall=0.68) +skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.95) +skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.99) +skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.76, is_error_page=0.95) +keep www.yahoo.com/ ``` The model is not deterministic, so expect the scores to move a little between -runs, and a borderline flag such as the empty search's to come and go. Some -sites change too: Yahoo only sometimes redirects to its consent page. +runs, and a borderline flag to come and go. Some sites change too: Yahoo only +sometimes redirects to its consent page, which is why it was flagged in the +first pass above and kept in the second. Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a release ships both, the script installs this checkout rather than the PyPI diff --git a/lightpanda/browser.py b/lightpanda/browser.py index 1bb9c99..41856ba 100644 --- a/lightpanda/browser.py +++ b/lightpanda/browser.py @@ -90,7 +90,7 @@ class PageVerdict: is_consent_wall: bool """A cookie consent banner covers the content.""" is_empty_catalog: bool - """The page says no matching products were found.""" + """A search or filter found nothing: no results, no matches, 0 items.""" is_error_page: bool """An error, such as page not found, stands in for the content.""" is_login_wall: bool From 0ab3d3ab97473b4eb943e2216e8f1cd325bbf8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 22:20:15 +0200 Subject: [PATCH 05/21] Cover classify's score questions Regenerated from a browser that accepts `{question, levels}`, and the mock TypeSafe server now answers score questions. --- lightpanda/_methods.py | 4 ++-- tests/test_classify.py | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/lightpanda/_methods.py b/lightpanda/_methods.py index fb827a5..bc27653 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -21,7 +21,7 @@ def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: - """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. Args: questions: JSON string: array of categories, or object of questions (`{}` for every preset) @@ -481,7 +481,7 @@ async def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError async def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: - """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), or `{question, options}` for a choice. A missing answer is null. + """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. Args: questions: JSON string: array of categories, or object of questions (`{}` for every preset) diff --git a/tests/test_classify.py b/tests/test_classify.py index 78872d5..a7586c0 100644 --- a/tests/test_classify.py +++ b/tests/test_classify.py @@ -8,7 +8,8 @@ class MockTypeSafe(http.server.BaseHTTPRequestHandler): - """Answers every question asked: 0.9 for a noul, the first option for a choice.""" + """Answers every question asked: 0.9 for a noul, the first option for a + choice, the top level for a score.""" def do_POST(self): request = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) @@ -16,6 +17,15 @@ def do_POST(self): for key, question in request["questions"].items(): if question["type"] == "noul": answers[key] = {"type": "noul", "noul": 0.9} + elif question["type"] == "score": + top = len(question["criteria"]) - 1 + answers[key] = { + "type": "score", + "score": top - 0.2, + "legend": {str(i): level for i, level in enumerate(question["criteria"])}, + "probabilities": {str(i): 0.8 if i == top else 0.2 / top for i in range(top + 1)}, + "confidence": 0.8, + } else: options = list(question["criteria"]) rest = 0.2 / max(len(options) - 1, 1) @@ -75,6 +85,17 @@ def test_classify_presets_and_questions(classify_browser, fixture_url): assert result["kind"]["choice"] == "home" +def test_classify_score(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/index.html") + result = page.classify( + questions={"completeness": {"question": "How complete is it?", "levels": ["empty", "partial", "full"]}} + ) + assert result["completeness"]["level"] == "full" + assert result["completeness"]["score"] == 1.8 + assert result["completeness"]["probabilities"] == {"empty": 0.1, "partial": 0.1, "full": 0.8} + + def test_judge(classify_browser, fixture_url): with classify_browser.new_session() as page: From dad96009ae9761b185fe6da3afa2371af4a3cb1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 23:09:52 +0200 Subject: [PATCH 06/21] Show a score question in the classify example The triage table gains a value column from a score question ("How much useful content would a scraper get from this page?" on none/little/plenty), so the example covers all three of Jev's question types. The README shows it, and why a score lands between levels. --- examples/README.md | 27 ++++++++++++++---------- examples/classify_pages.py | 43 +++++++++++++++++++++++++++++++------- 2 files changed, 52 insertions(+), 18 deletions(-) diff --git a/examples/README.md b/examples/README.md index ec18356..d99802f 100644 --- a/examples/README.md +++ b/examples/README.md @@ -221,8 +221,8 @@ later run instant. A 200 response can still be a consent wall, a bot check or an empty search. `classify` asks TypeSafe's page model about the rendered page, so a single call per URL tells you whether the page is worth extracting from and what -kind of page it is. One `questions` dict can mix presets, yes/no questions -and a choice: +kind of page it is. One `questions` dict can mix presets, yes/no questions, +a choice and a score: ```python answers = page.classify(questions={ @@ -230,6 +230,8 @@ answers = page.classify(questions={ "has_price": "Does the page show a price?", # yes/no -> probability "kind": {"question": "What kind of page is this?", "options": ["homepage", "listing", "product", "article", "search results", "login"]}, + "value": {"question": "How much useful content would a scraper get from this page?", + "levels": ["none", "little", "plenty"]}, # -> {"score": 1.28, "level": "little", ...} }) page.classify(questions=["software", "biology", "history"], selector="#bodyContent") # -> "software" ``` @@ -244,24 +246,27 @@ if not verdict.ok: ``` ``` -page kind price flags -quotes.toscrape.com/js/ homepage 0.01 - -books.toscrape.com/catalogue/a-light-in-the- product 1.00 - -en.wikipedia.org/wiki/Headless_browser article 0.01 - -news.ycombinator.com/login login 0.01 - -en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 isEmptyCatalog 0.99 -www.g2.com/ homepage 0.02 isBlocked 0.77 -www.yahoo.com/ article 0.01 isConsentWall 0.70 +page kind price value flags +quotes.toscrape.com/js/ homepage 0.01 plenty 1.75 - +books.toscrape.com/catalogue/a-light-in-the- product 1.00 plenty 1.95 - +en.wikipedia.org/wiki/Headless_browser article 0.02 plenty 1.56 - +news.ycombinator.com/login login 0.01 little 0.56 - +en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 none 0.41 isEmptyCatalog 0.99 +www.g2.com/ homepage 0.02 none 0.00 isBlocked 0.76 +www.yahoo.com/ article 0.01 little 1.28 isConsentWall 0.69 keep quotes.toscrape.com/js/ keep books.toscrape.com/catalogue/a-light-in-the- keep en.wikipedia.org/wiki/Headless_browser skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.95) skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.99) -skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.76, is_error_page=0.95) +skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.75, is_error_page=0.95) keep www.yahoo.com/ ``` +A score lands between its levels: Yahoo's consent page scores 1.28 on +none/little/plenty, and `level` names the nearest one. + The model is not deterministic, so expect the scores to move a little between runs, and a borderline flag to come and go. Some sites change too: Yahoo only sometimes redirects to its consent page, which is why it was flagged in the diff --git a/examples/classify_pages.py b/examples/classify_pages.py index e4e223c..3347066 100644 --- a/examples/classify_pages.py +++ b/examples/classify_pages.py @@ -16,6 +16,8 @@ - ``True`` asks a preset: isBlocked, isCaptcha, isConsentWall, isEmptyCatalog - a string asks a yes/no question and returns its probability - ``{"question", "options"}`` asks a choice +- ``{"question", "levels"}`` asks for a score on levels ordered low to high, + answering the ``score`` between them and the nearest ``level`` - a plain list of categories returns the one that fits When all you need is the gate, ``page.judge()`` asks every preset in one call @@ -42,14 +44,28 @@ ] QUESTIONS = { + # noul "isBlocked": True, "isCaptcha": True, "isConsentWall": True, "isEmptyCatalog": True, "has_price": "Does the page show a price?", + # choice "kind": { "question": "What kind of page is this?", - "options": ["homepage", "listing", "product", "article", "search results", "login"], + "options": [ + "homepage", + "listing", + "product", + "article", + "search results", + "login", + ], + }, + # score + "value": { + "question": "How much useful content would a scraper get from this page?", + "levels": ["none", "little", "plenty"], }, } @@ -62,25 +78,34 @@ def main() -> None: with Browser() as browser: if "classify" not in browser.tools: - sys.exit("This lightpanda binary has no classify tool; point LIGHTPANDA_BIN at a newer one.") + sys.exit( + "This lightpanda binary has no classify tool; point LIGHTPANDA_BIN at a newer one." + ) - print(f"{'page':<44} {'kind':<16} {'price':>5} flags") + print(f"{'page':<44} {'kind':<16} {'price':>5} {'value':<11} flags") for url in URLS: with browser.new_session() as page: page.goto(url=url) answers = page.classify(questions=QUESTIONS) kind = answers["kind"] - flags = ", ".join(f"{p} {answers[p]:.2f}" for p in PRESETS if answers[p] >= 0.5) + value = answers["value"] + flags = ", ".join( + f"{p} {answers[p]:.2f}" for p in PRESETS if answers[p] >= 0.5 + ) name = url.split("://", 1)[1][:44] print( - f"{name:<44} {kind['choice']:<16} {answers['has_price']:>5.2f} {flags or '-'}" + f"{name:<44} {kind['choice']:<16} {answers['has_price']:>5.2f} " + f"{value['level']:<6} {value['score']:.2f} {flags or '-'}" ) # A list of categories is the shortest form, and `selector` narrows the # question to one part of the page. with browser.new_session() as page: page.goto(url="https://en.wikipedia.org/wiki/Headless_browser") - topic = page.classify(questions=["software", "biology", "history", "sports"], selector="#bodyContent") + topic = page.classify( + questions=["software", "biology", "history", "sports"], + selector="#bodyContent", + ) print(f"\nWikipedia article body is about: {topic}") # judge() is the gate on its own: every preset, as bools. @@ -90,7 +115,11 @@ def main() -> None: page.goto(url=url) verdict = page.judge() name = url.split("://", 1)[1][:44] - print(f"keep {name}" if verdict.ok else f"skip {name:<44} {verdict.reason:<16} {verdict}") + print( + f"keep {name}" + if verdict.ok + else f"skip {name:<44} {verdict.reason:<16} {verdict}" + ) if __name__ == "__main__": From 674feb1fbfdca510db247fa897a0f937364cbe3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 1 Oct 2026 23:10:52 +0200 Subject: [PATCH 07/21] Refresh the classify example output for the tree-based state G2's DataDome CAPTCHA now reads as is_captcha, where the markdown state made it an error page. --- examples/README.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/examples/README.md b/examples/README.md index d99802f..469fce9 100644 --- a/examples/README.md +++ b/examples/README.md @@ -247,30 +247,31 @@ if not verdict.ok: ``` page kind price value flags -quotes.toscrape.com/js/ homepage 0.01 plenty 1.75 - -books.toscrape.com/catalogue/a-light-in-the- product 1.00 plenty 1.95 - +quotes.toscrape.com/js/ listing 0.01 plenty 1.95 - +books.toscrape.com/catalogue/a-light-in-the- product 0.99 plenty 1.91 - en.wikipedia.org/wiki/Headless_browser article 0.02 plenty 1.56 - -news.ycombinator.com/login login 0.01 little 0.56 - -en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 none 0.41 isEmptyCatalog 0.99 -www.g2.com/ homepage 0.02 none 0.00 isBlocked 0.76 -www.yahoo.com/ article 0.01 little 1.28 isConsentWall 0.69 +news.ycombinator.com/login login 0.01 little 0.62 - +en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 none 0.35 isEmptyCatalog 0.99 +www.g2.com/ homepage 0.02 none 0.02 isBlocked 0.97, isCaptcha 0.98 +www.yahoo.com/ homepage 0.09 little 1.44 - keep quotes.toscrape.com/js/ keep books.toscrape.com/catalogue/a-light-in-the- keep en.wikipedia.org/wiki/Headless_browser -skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.95) +skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.96) skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.99) -skip www.g2.com/ is_error_page PageVerdict(is_blocked=0.75, is_error_page=0.95) +skip www.g2.com/ is_captcha PageVerdict(is_blocked=0.97, is_captcha=0.98, is_error_page=0.82) keep www.yahoo.com/ ``` -A score lands between its levels: Yahoo's consent page scores 1.28 on -none/little/plenty, and `level` names the nearest one. +A score lands between its levels: Yahoo's homepage scores 1.44 on +none/little/plenty, and `level` names the nearest one. G2 shows checks stacking: +its DataDome CAPTCHA is also a block and an error page, and `reason` names the +strongest. The model is not deterministic, so expect the scores to move a little between runs, and a borderline flag to come and go. Some sites change too: Yahoo only -sometimes redirects to its consent page, which is why it was flagged in the -first pass above and kept in the second. +sometimes redirects to its consent page, and is then flagged `isConsentWall`. Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a release ships both, the script installs this checkout rather than the PyPI From 1b233cea71730d619c317bcd5aa704cfc9e5cf57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Fri, 2 Oct 2026 10:08:04 +0200 Subject: [PATCH 08/21] Simplify the classify example to one triage loop Each page loads once: judge() skips walls, CAPTCHAs and empty searches, and the rest get one classify call with a yes/no, a choice and a score. --- examples/README.md | 66 +++++++-------------- examples/classify_pages.py | 117 ++++++++----------------------------- 2 files changed, 46 insertions(+), 137 deletions(-) diff --git a/examples/README.md b/examples/README.md index 469fce9..ddaf72d 100644 --- a/examples/README.md +++ b/examples/README.md @@ -218,60 +218,36 @@ later run instant. ## `classify_pages.py` — triage a crawl before scraping it -A 200 response can still be a consent wall, a bot check or an empty search. -`classify` asks TypeSafe's page model about the rendered page, so a single -call per URL tells you whether the page is worth extracting from and what -kind of page it is. One `questions` dict can mix presets, yes/no questions, -a choice and a score: - -```python -answers = page.classify(questions={ - "isBlocked": True, "isConsentWall": True, "isEmptyCatalog": True, # presets - "has_price": "Does the page show a price?", # yes/no -> probability - "kind": {"question": "What kind of page is this?", - "options": ["homepage", "listing", "product", "article", "search results", "login"]}, - "value": {"question": "How much useful content would a scraper get from this page?", - "levels": ["none", "little", "plenty"]}, # -> {"score": 1.28, "level": "little", ...} -}) -page.classify(questions=["software", "biology", "history"], selector="#bodyContent") # -> "software" -``` - -When all you need is the gate, `page.judge()` asks every preset in one call -and answers with bools, keeping the probabilities in `scores`: +A 200 response can still be a login wall, a CAPTCHA or an empty search. +`page.judge()` asks TypeSafe's page model about the rendered page and says +whether to skip it, and why. For the pages worth keeping, `page.classify` +answers your own questions in one call: yes/no, a choice, or a score. ```python verdict = page.judge() if not verdict.ok: - print("skip", verdict.reason) # is_blocked + print("skip", verdict.reason) # is_captcha +else: + answers = page.classify(questions={ + "has_price": "Does the page show a price?", # -> 0.99 + "kind": {"question": "What kind of page is this?", + "options": ["product", "listing", "article", "other"]}, # -> {"choice": "product", ...} + "content": {"question": "How much useful content would a scraper get from this page?", + "levels": ["none", "little", "plenty"]}, # -> {"level": "plenty", "score": 1.94, ...} + }) ``` ``` -page kind price value flags -quotes.toscrape.com/js/ listing 0.01 plenty 1.95 - -books.toscrape.com/catalogue/a-light-in-the- product 0.99 plenty 1.91 - -en.wikipedia.org/wiki/Headless_browser article 0.02 plenty 1.56 - -news.ycombinator.com/login login 0.01 little 0.62 - -en.wikipedia.org/w/index.php?search=xqzzzvqk search results 0.01 none 0.35 isEmptyCatalog 0.99 -www.g2.com/ homepage 0.02 none 0.02 isBlocked 0.97, isCaptcha 0.98 -www.yahoo.com/ homepage 0.09 little 1.44 - - -keep quotes.toscrape.com/js/ -keep books.toscrape.com/catalogue/a-light-in-the- -keep en.wikipedia.org/wiki/Headless_browser -skip news.ycombinator.com/login is_login_wall PageVerdict(is_login_wall=0.96) -skip en.wikipedia.org/w/index.php?search=xqzzzvqk is_empty_catalog PageVerdict(is_empty_catalog=0.99) -skip www.g2.com/ is_captcha PageVerdict(is_blocked=0.97, is_captcha=0.98, is_error_page=0.82) -keep www.yahoo.com/ +keep books.toscrape.com/catalogue/a-light-in- product price 0.99 content plenty (1.94) +keep quotes.toscrape.com/js/ listing price 0.01 content plenty (1.90) +keep en.wikipedia.org/wiki/Headless_browser article price 0.02 content plenty (1.52) +skip news.ycombinator.com/login is_login_wall +skip en.wikipedia.org/w/index.php?search=xqzz is_empty_catalog +skip www.g2.com/ is_captcha ``` -A score lands between its levels: Yahoo's homepage scores 1.44 on -none/little/plenty, and `level` names the nearest one. G2 shows checks stacking: -its DataDome CAPTCHA is also a block and an error page, and `reason` names the -strongest. - -The model is not deterministic, so expect the scores to move a little between -runs, and a borderline flag to come and go. Some sites change too: Yahoo only -sometimes redirects to its consent page, and is then flagged `isConsentWall`. +A score falls between its levels (0 = none, 2 = plenty). Scores vary a little +between runs. Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a release ships both, the script installs this checkout rather than the PyPI diff --git a/examples/classify_pages.py b/examples/classify_pages.py index 3347066..0613e1f 100644 --- a/examples/classify_pages.py +++ b/examples/classify_pages.py @@ -6,121 +6,54 @@ # [tool.uv.sources] # lightpanda = { path = "..", editable = true } # /// -"""Triage a crawl: ask each page what it is before scraping it. +"""Triage a crawl: skip pages that are walls, CAPTCHAs or empty searches with +``page.judge()``, then ask the rest your own questions with ``page.classify``. -A scraper that gets HTTP 200 can still be looking at a cookie wall, a bot -check or a search with no results. ``classify`` asks TypeSafe's page model -about the rendered page, so one call per URL says whether the page is worth -extracting from and what kind of page it is: - -- ``True`` asks a preset: isBlocked, isCaptcha, isConsentWall, isEmptyCatalog -- a string asks a yes/no question and returns its probability -- ``{"question", "options"}`` asks a choice -- ``{"question", "levels"}`` asks for a score on levels ordered low to high, - answering the ``score`` between them and the nearest ``level`` -- a plain list of categories returns the one that fits - -When all you need is the gate, ``page.judge()`` asks every preset in one call -and answers with bools: ``ok`` is true when none of them fired. - -Needs TYPESAFE_API_KEY in the environment. - -Run: uv run examples/classify_pages.py +Needs TYPESAFE_API_KEY. Run: uv run examples/classify_pages.py """ -import os -import sys - from lightpanda import Browser URLS = [ - "https://quotes.toscrape.com/js/", "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", + "https://quotes.toscrape.com/js/", "https://en.wikipedia.org/wiki/Headless_browser", "https://news.ycombinator.com/login", - "https://en.wikipedia.org/w/index.php?search=xqzzzvqk+plorbt&fulltext=1&ns0=1", + "https://en.wikipedia.org/w/index.php?search=xqzzzvqk+plorbt&fulltext=1", "https://www.g2.com/", - "https://www.yahoo.com/", ] QUESTIONS = { - # noul - "isBlocked": True, - "isCaptcha": True, - "isConsentWall": True, - "isEmptyCatalog": True, + # yes/no "has_price": "Does the page show a price?", # choice "kind": { "question": "What kind of page is this?", - "options": [ - "homepage", - "listing", - "product", - "article", - "search results", - "login", - ], + "options": ["product", "listing", "article", "other"], }, # score - "value": { + "content": { "question": "How much useful content would a scraper get from this page?", "levels": ["none", "little", "plenty"], }, } -PRESETS = ["isBlocked", "isCaptcha", "isConsentWall", "isEmptyCatalog"] - - -def main() -> None: - if not os.environ.get("TYPESAFE_API_KEY"): - sys.exit("Set TYPESAFE_API_KEY to use classify.") - - with Browser() as browser: - if "classify" not in browser.tools: - sys.exit( - "This lightpanda binary has no classify tool; point LIGHTPANDA_BIN at a newer one." - ) - - print(f"{'page':<44} {'kind':<16} {'price':>5} {'value':<11} flags") - for url in URLS: - with browser.new_session() as page: - page.goto(url=url) - answers = page.classify(questions=QUESTIONS) - kind = answers["kind"] - value = answers["value"] - flags = ", ".join( - f"{p} {answers[p]:.2f}" for p in PRESETS if answers[p] >= 0.5 - ) - name = url.split("://", 1)[1][:44] - print( - f"{name:<44} {kind['choice']:<16} {answers['has_price']:>5.2f} " - f"{value['level']:<6} {value['score']:.2f} {flags or '-'}" - ) - - # A list of categories is the shortest form, and `selector` narrows the - # question to one part of the page. +with Browser() as browser: + for url in URLS: + name = url.split("://", 1)[1][:40] with browser.new_session() as page: - page.goto(url="https://en.wikipedia.org/wiki/Headless_browser") - topic = page.classify( - questions=["software", "biology", "history", "sports"], - selector="#bodyContent", + page.goto(url=url) + + verdict = page.judge() + if not verdict.ok: + print(f"skip {name:<40} {verdict.reason}") + continue + + answers = page.classify(questions=QUESTIONS) + kind = answers["kind"]["choice"] + price = answers["has_price"] + content = answers["content"] + print( + f"keep {name:<40} {kind:<8} price {price:.2f} " + f"content {content['level']} ({content['score']:.2f})" ) - print(f"\nWikipedia article body is about: {topic}") - - # judge() is the gate on its own: every preset, as bools. - print() - for url in URLS: - with browser.new_session() as page: - page.goto(url=url) - verdict = page.judge() - name = url.split("://", 1)[1][:44] - print( - f"keep {name}" - if verdict.ok - else f"skip {name:<44} {verdict.reason:<16} {verdict}" - ) - - -if __name__ == "__main__": - main() From 10d7207836fa3f869c77af575682452bc6664f01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Tue, 13 Oct 2026 22:31:38 +0200 Subject: [PATCH 09/21] Let judge() ask your own questions in the same call `page.judge(questions=...)` sends them with `presets: true`, so one TypeSafe call answers the walls and the caller's questions; the answers land in `verdict.answers`. Without questions it sends `{}` as before, so it still works against a browser without the option. --- lightpanda/_methods.py | 10 ++++++---- lightpanda/async_browser.py | 4 ++-- lightpanda/browser.py | 38 +++++++++++++++++++++++++++++-------- tests/test_classify.py | 15 +++++++++++++++ 4 files changed, 53 insertions(+), 14 deletions(-) diff --git a/lightpanda/_methods.py b/lightpanda/_methods.py index bc27653..7219494 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -20,14 +20,15 @@ class SessionMethods: def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError - def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: + def classify(self, *, questions: str | dict | list, selector: str | None = None, presets: bool | None = None) -> Any: """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. Args: questions: JSON string: array of categories, or object of questions (`{}` for every preset) selector: Optional CSS selector to classify a specific element subtree instead of the full page + presets: Also ask every preset in the same call, each answered under its own name beside the questions. Needs the object form. """ - return self.call("classify", questions=questions, selector=selector) + return self.call("classify", questions=questions, selector=selector, presets=presets) def click(self, *, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Click on an interactive element. Provide either a CSS selector (preferred for reproducibility) or a backendNodeId. Returns the current page URL and title after the click. @@ -480,14 +481,15 @@ class AsyncSessionMethods: async def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError - async def classify(self, *, questions: str | dict | list, selector: str | None = None) -> Any: + async def classify(self, *, questions: str | dict | list, selector: str | None = None, presets: bool | None = None) -> Any: """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. Args: questions: JSON string: array of categories, or object of questions (`{}` for every preset) selector: Optional CSS selector to classify a specific element subtree instead of the full page + presets: Also ask every preset in the same call, each answered under its own name beside the questions. Needs the object form. """ - return await self.call("classify", questions=questions, selector=selector) + return await self.call("classify", questions=questions, selector=selector, presets=presets) async def click(self, *, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Click on an interactive element. Provide either a CSS selector (preferred for reproducibility) or a backendNodeId. Returns the current page URL and title after the click. diff --git a/lightpanda/async_browser.py b/lightpanda/async_browser.py index 0d74469..6b743f1 100644 --- a/lightpanda/async_browser.py +++ b/lightpanda/async_browser.py @@ -58,9 +58,9 @@ async def call(self, tool: str, **kwargs): return [AsyncElement(node, self) if isinstance(node, Element) else node for node in result] return result - async def judge(self, *, threshold: float = 0.5) -> PageVerdict: + async def judge(self, *, questions: dict | None = None, threshold: float = 0.5) -> PageVerdict: """Judge whether the page is worth reading; see :meth:`Session.judge`.""" - return await _run(self._executor, self._session.judge, threshold=threshold) + return await _run(self._executor, self._session.judge, questions=questions, threshold=threshold) def __getattr__(self, attr: str): session = self.__dict__.get("_session") diff --git a/lightpanda/browser.py b/lightpanda/browser.py index 41856ba..d7b15d2 100644 --- a/lightpanda/browser.py +++ b/lightpanda/browser.py @@ -17,7 +17,7 @@ import os import re import subprocess -from collections.abc import Sequence +from collections.abc import Iterable, Sequence from importlib.metadata import PackageNotFoundError, version from pathlib import Path @@ -81,6 +81,9 @@ class PageVerdict: print("skipping:", verdict.reason) # is_paywall verdict.scores["is_blocked"] # 0.03 ``` + + Questions passed to :meth:`Session.judge` are asked in the same call, and + their answers land in :attr:`answers`. """ is_blocked: bool @@ -105,9 +108,15 @@ class PageVerdict: text). A page that is blank while it loads says nothing, so this misses it.""" scores: dict[str, float | None] """Each check's probability, keyed by its attribute name.""" - - def __init__(self, answers: dict, threshold: float): - self.scores = {_snake(preset): score for preset, score in answers.items()} + answers: dict + """The answers to the questions passed to :meth:`Session.judge`, keyed as + asked and shaped as :meth:`Session.classify` returns them. Empty when none + were passed.""" + + def __init__(self, answers: dict, threshold: float, asked: Iterable[str] = ()): + asked = set(asked) + self.answers = {key: answers.get(key) for key in asked} + self.scores = {_snake(preset): score for preset, score in answers.items() if preset not in asked} for attr, score in self.scores.items(): setattr(self, attr, score is not None and score >= threshold) @@ -283,17 +292,30 @@ def call(self, tool: str, **kwargs): return [Element(node, self) for node in parsed] return parsed - def judge(self, *, threshold: float = 0.5) -> PageVerdict: + def judge(self, *, questions: dict | None = None, threshold: float = 0.5) -> PageVerdict: """Judge whether the page is worth reading: blocked, a login wall, a paywall, an error page and the rest of the ``classify`` presets, in a single call. + Your own questions can ride along in that call instead of a second + :meth:`classify`, which costs a whole round trip to the model; their + answers land in :attr:`PageVerdict.answers`: + + ```python + verdict = page.judge(questions={"has_price": "Does the page show a price?"}) + if verdict.ok: + print(verdict.answers["has_price"]) # 0.99 + ``` + Args: + questions: Questions in the object form :meth:`classify` takes. threshold: The probability at which a check counts as true. """ - # An empty questions object asks the browser for every preset. - answers = self.call("classify", questions={}) - return PageVerdict(answers, threshold) + if not questions: + # An empty questions object asks the browser for every preset. + return PageVerdict(self.call("classify", questions={}), threshold) + answers = self.call("classify", questions=questions, presets=True) + return PageVerdict(answers, threshold, asked=questions) def _resolve(self, attr: str) -> str | None: """The tool name behind a snake_case public attribute, if any.""" diff --git a/tests/test_classify.py b/tests/test_classify.py index a7586c0..4bd815a 100644 --- a/tests/test_classify.py +++ b/tests/test_classify.py @@ -109,6 +109,21 @@ def test_judge(classify_browser, fixture_url): assert page.judge(threshold=0.95).reason is None +def test_judge_with_questions(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/index.html") + verdict = page.judge( + questions={ + "has_price": "Does the page show a price?", + "kind": {"question": "What kind of page?", "options": ["home", "article"]}, + } + ) + assert verdict.answers["has_price"] == 0.9 + assert verdict.answers["kind"]["choice"] == "home" + assert "has_price" not in verdict.scores and "kind" not in verdict.scores + assert verdict.is_login_wall and not verdict.ok + + async def test_judge_async(classify_browser, fixture_url): from lightpanda import AsyncBrowser From c6f2ab6c2b14a7a3dff96718e527184dc41ca19c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Tue, 13 Oct 2026 22:31:38 +0200 Subject: [PATCH 10/21] Triage each page with one judge() call in the classify example The example asks its questions through judge() instead of a second classify(), and prints each page's load and Jev time. --- examples/README.md | 37 +++++++++++++++++++------------------ examples/classify_pages.py | 26 ++++++++++++++++++-------- 2 files changed, 37 insertions(+), 26 deletions(-) diff --git a/examples/README.md b/examples/README.md index ddaf72d..10dc0f4 100644 --- a/examples/README.md +++ b/examples/README.md @@ -220,34 +220,35 @@ later run instant. A 200 response can still be a login wall, a CAPTCHA or an empty search. `page.judge()` asks TypeSafe's page model about the rendered page and says -whether to skip it, and why. For the pages worth keeping, `page.classify` -answers your own questions in one call: yes/no, a choice, or a score. +whether to skip it, and why. Your own questions ride along in the same call, +yes/no, a choice, or a score, so each page costs one round trip: ```python -verdict = page.judge() +verdict = page.judge(questions={ + "has_price": "Does the page show a price?", # -> 0.99 + "kind": {"question": "What kind of page is this?", + "options": ["product", "listing", "article", "other"]}, # -> {"choice": "product", ...} + "content": {"question": "How much useful content would a scraper get from this page?", + "levels": ["none", "little", "plenty"]}, # -> {"level": "plenty", "score": 1.90, ...} +}) if not verdict.ok: - print("skip", verdict.reason) # is_captcha + print("skip", verdict.reason) # is_captcha else: - answers = page.classify(questions={ - "has_price": "Does the page show a price?", # -> 0.99 - "kind": {"question": "What kind of page is this?", - "options": ["product", "listing", "article", "other"]}, # -> {"choice": "product", ...} - "content": {"question": "How much useful content would a scraper get from this page?", - "levels": ["none", "little", "plenty"]}, # -> {"level": "plenty", "score": 1.94, ...} - }) + print(verdict.answers["kind"]["choice"]) # product ``` ``` -keep books.toscrape.com/catalogue/a-light-in- product price 0.99 content plenty (1.94) -keep quotes.toscrape.com/js/ listing price 0.01 content plenty (1.90) -keep en.wikipedia.org/wiki/Headless_browser article price 0.02 content plenty (1.52) -skip news.ycombinator.com/login is_login_wall -skip en.wikipedia.org/w/index.php?search=xqzz is_empty_catalog -skip www.g2.com/ is_captcha +keep books.toscrape.com/catalogue/a-light-in- product price 0.99 content plenty (1.90) [load 1.34s, jev 0.50s] +keep quotes.toscrape.com/js/ listing price 0.01 content plenty (1.92) [load 0.83s, jev 0.35s] +keep en.wikipedia.org/wiki/Headless_browser article price 0.02 content plenty (1.78) [load 0.64s, jev 0.37s] +skip news.ycombinator.com/login is_login_wall [load 0.64s, jev 0.32s] +skip en.wikipedia.org/w/index.php?search=xqzz is_empty_catalog [load 1.39s, jev 0.25s] +skip www.g2.com/ is_captcha [load 0.19s, jev 0.24s] ``` A score falls between its levels (0 = none, 2 = plenty). Scores vary a little -between runs. +between runs. The `jev` time is the whole call: the browser reading the page, +then the round trip to TypeSafe, which reuses one connection after the first. Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a release ships both, the script installs this checkout rather than the PyPI diff --git a/examples/classify_pages.py b/examples/classify_pages.py index 0613e1f..eed6edc 100644 --- a/examples/classify_pages.py +++ b/examples/classify_pages.py @@ -6,12 +6,14 @@ # [tool.uv.sources] # lightpanda = { path = "..", editable = true } # /// -"""Triage a crawl: skip pages that are walls, CAPTCHAs or empty searches with -``page.judge()``, then ask the rest your own questions with ``page.classify``. +"""Triage a crawl: ``page.judge()`` says whether each page is a wall, a CAPTCHA +or an empty search, and answers your own questions in the same call. Needs TYPESAFE_API_KEY. Run: uv run examples/classify_pages.py """ +from time import perf_counter + from lightpanda import Browser URLS = [ @@ -38,22 +40,30 @@ }, } + +def timed(call, **kwargs): + """The call's result and the seconds it took.""" + start = perf_counter() + return call(**kwargs), perf_counter() - start + + with Browser() as browser: for url in URLS: name = url.split("://", 1)[1][:40] with browser.new_session() as page: - page.goto(url=url) - - verdict = page.judge() + _, load = timed(page.goto, url=url) + # One call: every preset, plus our own questions. + verdict, jev = timed(page.judge, questions=QUESTIONS) + times = f"[load {load:.2f}s, jev {jev:.2f}s]" if not verdict.ok: - print(f"skip {name:<40} {verdict.reason}") + print(f"skip {name:<40} {verdict.reason:<38} {times}") continue - answers = page.classify(questions=QUESTIONS) + answers = verdict.answers kind = answers["kind"]["choice"] price = answers["has_price"] content = answers["content"] print( f"keep {name:<40} {kind:<8} price {price:.2f} " - f"content {content['level']} ({content['score']:.2f})" + f"content {content['level']} ({content['score']:.2f}) {times}" ) From 7e1dd3aeec9e873e3d2713871ec41fb95cc95b94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Tue, 13 Oct 2026 23:26:04 +0200 Subject: [PATCH 11/21] Refresh the classify example timings from a release build --- examples/README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/examples/README.md b/examples/README.md index 10dc0f4..408495c 100644 --- a/examples/README.md +++ b/examples/README.md @@ -238,12 +238,12 @@ else: ``` ``` -keep books.toscrape.com/catalogue/a-light-in- product price 0.99 content plenty (1.90) [load 1.34s, jev 0.50s] -keep quotes.toscrape.com/js/ listing price 0.01 content plenty (1.92) [load 0.83s, jev 0.35s] -keep en.wikipedia.org/wiki/Headless_browser article price 0.02 content plenty (1.78) [load 0.64s, jev 0.37s] -skip news.ycombinator.com/login is_login_wall [load 0.64s, jev 0.32s] -skip en.wikipedia.org/w/index.php?search=xqzz is_empty_catalog [load 1.39s, jev 0.25s] -skip www.g2.com/ is_captcha [load 0.19s, jev 0.24s] +keep books.toscrape.com/catalogue/a-light-in- product price 0.99 content plenty (1.94) [load 1.11s, jev 0.37s] +keep quotes.toscrape.com/js/ listing price 0.01 content plenty (1.91) [load 0.95s, jev 0.23s] +keep en.wikipedia.org/wiki/Headless_browser article price 0.02 content plenty (1.74) [load 0.59s, jev 0.25s] +skip news.ycombinator.com/login is_login_wall [load 0.57s, jev 0.23s] +skip en.wikipedia.org/w/index.php?search=xqzz is_empty_catalog [load 1.18s, jev 0.26s] +skip www.g2.com/ is_captcha [load 0.16s, jev 0.20s] ``` A score falls between its levels (0 = none, 2 = plenty). Scores vary a little From fe05971ca7129cd61cbd76facfa5184f335ab6ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Wed, 14 Oct 2026 11:16:51 +0200 Subject: [PATCH 12/21] Add a parallel crawl example that acts on Jev's verdicts triage_crawl.py judges 29 real pages with six browsers at once. The verdict drives the crawler: accept a cookie wall and look again, back off when the page says we are going too fast (our own question, asked in the same call), wait for a page still loading, or skip it and say why. It ends with the counts and Jev's median and p90 call time. --- examples/README.md | 79 ++++++++++++++++ examples/triage_crawl.py | 194 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 273 insertions(+) create mode 100644 examples/triage_crawl.py diff --git a/examples/README.md b/examples/README.md index 408495c..fdeec8a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,6 +8,7 @@ uv run examples/quotes_analysis.py uv run examples/compare.py --repeat 5 uv run examples/neurips_topics.py uv run examples/classify_pages.py # needs TYPESAFE_API_KEY +uv run examples/triage_crawl.py # needs TYPESAFE_API_KEY ``` Set `LIGHTPANDA_BIN=/path/to/lightpanda` to run against a local browser build @@ -257,3 +258,81 @@ package, so run it from here against a local browser build: ```bash LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages.py ``` + +## `triage_crawl.py` — crawl real sites in parallel and act on what Jev sees + +The same `judge()` call over 29 real pages, six browsers at a time. The +verdict decides what the crawler does next: accept a cookie wall and look +again, back off when the site says we are going too fast, wait for a page +that is still loading, or skip the page and say why. "Too fast" is our own +question, asked in the same call as the wall checks: + +```python +QUESTIONS = { + "rate_limited": "Does the page say we sent too many requests and should slow down or retry later?", + "kind": {"question": "What kind of page is this?", + "options": ["product", "listing", "article", "docs", "search", "other"]}, +} + +verdict = await page.judge(questions=QUESTIONS) +if verdict.answers["rate_limited"] >= 0.5: + await asyncio.sleep(3) # and load it again +elif verdict.is_consent_wall: + found = await page.find_element(role="button", name="/^(accept|aceptar|akzeptieren)/i") + await page.click(backend_node_id=found[0]["backendNodeId"]) +``` + +``` +keep docs.python.org/3/library/asyncio.html docs 0.64s +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.84s +keep en.wikipedia.org/wiki/Headless_browser article 0.91s +keep quotes.toscrape.com/js/ listing 1.25s +keep en.wikipedia.org/wiki/Web_scraping article 1.56s +keep books.toscrape.com/catalogue/a-light-in-the- product 1.58s +keep lobste.rs/ listing 1.00s +keep github.com/lightpanda-io/browser listing 1.62s +keep www.spiegel.de/ listing 1.81s +skip github.com/settings/profile login wall 0.77s +skip www.g2.com/ blocked 0.37s +skip www.wsj.com/ captcha 0.42s +skip www.linkedin.com/feed/ login wall 1.65s +keep www.indeed.com/ search 2.93s <- accepted cookies +skip pypi.org/project/lightpanda/ captcha 0.44s +skip stackoverflow.com/questions/231767/what-does blocked 0.47s +skip www.zeit.de/index error page 0.36s +skip www.economist.com/leaders/2024/01/04/what-to blocked 1.48s +skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 0.55s +skip web.whatsapp.com/ unsupported browser 0.75s +keep news.ycombinator.com/ listing 4.72s <- backed off +skip news.ycombinator.com/login login wall 4.32s <- backed off +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.05s +skip arxiv.org/abs/1706.03762 error page 0.27s +skip www.python.org/no-such-page error page 0.78s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.61s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.25s +skip github.com/lightpanda-io/does-not-exist error page 1.13s +keep news.ycombinator.com/newest listing 11.11s <- backed off, backed off + +29 pages in 12.7s with 6 browsers (46.6s of page time): 12 kept, 17 skipped +Jev: 34 calls, median 0.22s, p90 0.30s +skipped: error page 5, login wall 3, blocked 3, empty catalog 3, captcha 2, unsupported browser 1 +acted: backed off 4, accepted cookies 1 +``` + +What the skipped pages actually showed: Indeed's cookie wall is in Spanish, +Zeit's is a German notice that it reserves its content against data mining, +PyPI's is a Fastly challenge, arXiv's is a bare Varnish 403, eBay's is "Something +went wrong on our end", and Stack Overflow's is empty. Hacker News rate-limits +three tabs opened at once, and says so in a sentence the crawler had no rule for. + +Sites change and the model is not deterministic, so a run differs a little: +how often Hacker News pushes back, or whether a challenge page scores as +`blocked` or `captcha`. A browser loads one page at a time, which is why the +script runs several. Known misses: Zillow's home page scores as an empty search, +and Le Monde's front page leans paywall (0.71). + +Runs from this checkout against a local browser build, like `classify_pages.py`: + +```bash +LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/triage_crawl.py +``` diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py new file mode 100644 index 0000000..87c7a48 --- /dev/null +++ b/examples/triage_crawl.py @@ -0,0 +1,194 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["lightpanda"] +# +# # judge() is not on PyPI yet: use this checkout until it is. +# [tool.uv.sources] +# lightpanda = { path = "..", editable = true } +# /// +"""Triage a crawl of real sites in parallel, and act on what Jev sees. + +Each page gets one ``page.judge()`` call: every wall check plus our own +questions. The verdict decides what happens next: accept a cookie wall and +look again, back off when the site says we are going too fast, wait for a +page that is still loading, or skip the page and say why. + +Needs TYPESAFE_API_KEY. Run: uv run examples/triage_crawl.py +""" + +import asyncio +import statistics +import sys +from collections import Counter +from time import perf_counter + +from lightpanda import AsyncBrowser, LightpandaError + +# A browser loads one page at a time, so a crawl runs several. +BROWSERS = 6 + +URLS = [ + # content + "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", + "https://quotes.toscrape.com/js/", + "https://en.wikipedia.org/wiki/Headless_browser", + "https://en.wikipedia.org/wiki/Web_scraping", + "https://docs.python.org/3/library/asyncio.html", + "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API", + "https://github.com/lightpanda-io/browser", + "https://lobste.rs/", + "https://www.spiegel.de/", + "https://news.ycombinator.com/", + "https://news.ycombinator.com/newest", + # a cookie wall in front of the content + "https://www.indeed.com/", + # walls + "https://news.ycombinator.com/login", + "https://github.com/settings/profile", + "https://www.linkedin.com/feed/", + "https://www.g2.com/", + "https://www.wsj.com/", + "https://www.economist.com/leaders/2024/01/04/what-to-expect-in-2024", + "https://pypi.org/project/lightpanda/", + "https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python", + "https://www.zeit.de/index", + "https://web.whatsapp.com/", + # dead ends + "https://www.npmjs.com/search?q=xqzzzvqkplorbt", + "https://github.com/search?q=xqzzzvqkplorbt&type=repositories", + "https://en.wikipedia.org/w/index.php?search=xqzzzvqk+plorbt&fulltext=1", + "https://www.python.org/no-such-page", + "https://github.com/lightpanda-io/does-not-exist", + "https://arxiv.org/abs/1706.03762", + "https://www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt", +] + +QUESTIONS = { + "rate_limited": "Does the page say we sent too many requests and should slow down or retry later?", + "kind": { + "question": "What kind of page is this?", + "options": ["product", "listing", "article", "docs", "search", "other"], + }, +} + +# Accept buttons start with one of these, in the languages we crawl. +ACCEPT = "/^(accept|aceptar|accepter|akzeptieren|agree|allow)/i" + +TTY = sys.stdout.isatty() + + +def paint(text, color): + codes = {"green": "32", "red": "31", "yellow": "33", "dim": "2"} + return f"\033[{codes[color]}m{text}\033[0m" if TTY else text + + +def label(reason): + """is_empty_catalog -> empty catalog""" + return reason.removeprefix("is_").replace("_", " ") + + +async def judge(page, jev_times): + start = perf_counter() + verdict = await page.judge(questions=QUESTIONS) + jev_times.append(perf_counter() - start) + return verdict + + +async def accept_cookies(page): + """Click the wall's accept button. False when there is none to click.""" + found = await page.find_element(role="button", name=ACCEPT) + if not found: + return False + await page.click(backend_node_id=found[0]["backendNodeId"]) + # Banners fade out after the click. + await page.wait_for_state(state="networkidle") + return True + + +async def visit(page, url, jev_times): + """Load `url`, judge it, act on the verdict. Returns (verdict, actions).""" + actions = [] + await page.goto(url=url) + verdict = await judge(page, jev_times) + for _ in range(3): + if verdict.answers["rate_limited"] >= 0.5 and actions.count("backed off") < 2: + actions.append("backed off") + await asyncio.sleep(3 * actions.count("backed off")) + await page.goto(url=url) + elif verdict.is_consent_wall and "accepted cookies" not in actions and await accept_cookies(page): + actions.append("accepted cookies") + elif verdict.is_loading and "waited" not in actions: + actions.append("waited") + await page.wait_for_state(state="networkidle") + else: + break + verdict = await judge(page, jev_times) + return verdict, actions + + +def outcome(verdict): + """Either "kept" or why the page was skipped.""" + if verdict.answers["rate_limited"] >= 0.5: + return "rate limited" + return "kept" if verdict.ok else label(verdict.reason) + + +async def crawl(browser, queue, results, jev_times): + while not queue.empty(): + url = queue.get_nowait() + name = url.split("://", 1)[1][:44] + start = perf_counter() + async with await browser.new_session() as page: + try: + verdict, actions = await visit(page, url, jev_times) + except LightpandaError as err: + print(f"{paint('fail', 'red')} {name:<44} {err}") + results.append(("failed", [], perf_counter() - start)) + continue + took = perf_counter() - start + acted = paint(f" <- {', '.join(actions)}", "yellow") if actions else "" + result = outcome(verdict) + if result == "kept": + line = f"{paint('keep', 'green')} {name:<44} {verdict.answers['kind']['choice']:<22}" + else: + line = f"{paint('skip', 'red')} {name:<44} {result:<22}" + print(f"{line} {paint(f'{took:.2f}s', 'dim')}{acted}") + results.append((result, actions, took)) + + +async def main(): + queue = asyncio.Queue() + for url in URLS: + queue.put_nowait(url) + results, jev_times = [], [] + + start = perf_counter() + browsers = [AsyncBrowser() for _ in range(BROWSERS)] + try: + await asyncio.gather(*(b.start() for b in browsers)) + await asyncio.gather(*(crawl(b, queue, results, jev_times) for b in browsers)) + finally: + await asyncio.gather(*(b.close() for b in browsers)) + elapsed = perf_counter() - start + + outcomes = Counter(result for result, _, _ in results) + kept = outcomes.pop("kept", 0) + acted = Counter(action for _, actions, _ in results for action in actions) + page_time = sum(took for _, _, took in results) + jev_times.sort() + + print() + print( + f"{len(results)} pages in {elapsed:.1f}s with {BROWSERS} browsers " + f"({page_time:.1f}s of page time): {kept} kept, {len(results) - kept} skipped" + ) + print( + f"Jev: {len(jev_times)} calls, median {statistics.median(jev_times):.2f}s, " + f"p90 {jev_times[int(len(jev_times) * 0.9)]:.2f}s" + ) + print("skipped: " + ", ".join(f"{reason} {n}" for reason, n in outcomes.most_common())) + if acted: + print("acted: " + ", ".join(f"{action} {n}" for action, n in acted.most_common())) + + +asyncio.run(main()) From d614a4c4f990c33c5bc7a8195715394d65d5220a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 15 Oct 2026 10:02:34 +0200 Subject: [PATCH 13/21] Crawl with one browser in the triage example Each crawler drives its own session, and the browser now loads their pages in parallel, so the example no longer starts one browser per crawler. --- examples/README.md | 78 ++++++++++++++++++++-------------------- examples/triage_crawl.py | 14 +++----- 2 files changed, 44 insertions(+), 48 deletions(-) diff --git a/examples/README.md b/examples/README.md index fdeec8a..522b884 100644 --- a/examples/README.md +++ b/examples/README.md @@ -261,7 +261,7 @@ LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages. ## `triage_crawl.py` — crawl real sites in parallel and act on what Jev sees -The same `judge()` call over 29 real pages, six browsers at a time. The +The same `judge()` call over 29 real pages, six at a time in one browser. The verdict decides what the crawler does next: accept a cookie wall and look again, back off when the site says we are going too fast, wait for a page that is still loading, or skip the page and say why. "Too fast" is our own @@ -283,53 +283,53 @@ elif verdict.is_consent_wall: ``` ``` -keep docs.python.org/3/library/asyncio.html docs 0.64s -keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.84s -keep en.wikipedia.org/wiki/Headless_browser article 0.91s -keep quotes.toscrape.com/js/ listing 1.25s -keep en.wikipedia.org/wiki/Web_scraping article 1.56s -keep books.toscrape.com/catalogue/a-light-in-the- product 1.58s -keep lobste.rs/ listing 1.00s -keep github.com/lightpanda-io/browser listing 1.62s -keep www.spiegel.de/ listing 1.81s -skip github.com/settings/profile login wall 0.77s -skip www.g2.com/ blocked 0.37s -skip www.wsj.com/ captcha 0.42s -skip www.linkedin.com/feed/ login wall 1.65s -keep www.indeed.com/ search 2.93s <- accepted cookies -skip pypi.org/project/lightpanda/ captcha 0.44s -skip stackoverflow.com/questions/231767/what-does blocked 0.47s -skip www.zeit.de/index error page 0.36s -skip www.economist.com/leaders/2024/01/04/what-to blocked 1.48s -skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 0.55s -skip web.whatsapp.com/ unsupported browser 0.75s -keep news.ycombinator.com/ listing 4.72s <- backed off -skip news.ycombinator.com/login login wall 4.32s <- backed off -skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.05s -skip arxiv.org/abs/1706.03762 error page 0.27s -skip www.python.org/no-such-page error page 0.78s -skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.61s -skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.25s -skip github.com/lightpanda-io/does-not-exist error page 1.13s -keep news.ycombinator.com/newest listing 11.11s <- backed off, backed off - -29 pages in 12.7s with 6 browsers (46.6s of page time): 12 kept, 17 skipped -Jev: 34 calls, median 0.22s, p90 0.30s -skipped: error page 5, login wall 3, blocked 3, empty catalog 3, captcha 2, unsupported browser 1 -acted: backed off 4, accepted cookies 1 +keep docs.python.org/3/library/asyncio.html docs 0.73s +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.95s +keep en.wikipedia.org/wiki/Web_scraping article 1.03s +keep en.wikipedia.org/wiki/Headless_browser article 1.04s +keep quotes.toscrape.com/js/ listing 1.17s +keep books.toscrape.com/catalogue/a-light-in-the- product 1.28s +keep lobste.rs/ listing 0.85s +keep www.spiegel.de/ listing 1.60s +keep github.com/lightpanda-io/browser listing 2.54s +skip github.com/settings/profile login wall 1.14s +keep www.indeed.com/ search 2.84s <- accepted cookies +skip www.g2.com/ blocked 0.42s +skip www.wsj.com/ blocked 0.41s +skip www.linkedin.com/feed/ login wall 1.49s +skip www.economist.com/leaders/2024/01/04/what-to blocked 0.60s +skip www.zeit.de/index error page 0.38s +skip stackoverflow.com/questions/231767/what-does blocked 0.43s +keep pypi.org/project/lightpanda/ listing 0.77s +keep news.ycombinator.com/ listing 4.54s <- backed off +keep news.ycombinator.com/newest listing 4.90s <- backed off +skip news.ycombinator.com/login login wall 4.30s <- backed off +skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 0.98s +skip web.whatsapp.com/ unsupported browser 1.12s +skip arxiv.org/abs/1706.03762 error page 0.29s +skip www.python.org/no-such-page error page 0.66s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.57s +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.74s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.63s +skip github.com/lightpanda-io/does-not-exist error page 1.85s + +29 pages in 8.2s with 6 crawlers (42.3s of page time): 13 kept, 16 skipped +Jev: 33 calls, median 0.22s, p90 0.48s +skipped: error page 5, blocked 4, login wall 3, empty catalog 3, unsupported browser 1 +acted: backed off 3, accepted cookies 1 ``` What the skipped pages actually showed: Indeed's cookie wall is in Spanish, Zeit's is a German notice that it reserves its content against data mining, -PyPI's is a Fastly challenge, arXiv's is a bare Varnish 403, eBay's is "Something +arXiv's is a bare Varnish 403, eBay's is "Something went wrong on our end", and Stack Overflow's is empty. Hacker News rate-limits three tabs opened at once, and says so in a sentence the crawler had no rule for. Sites change and the model is not deterministic, so a run differs a little: how often Hacker News pushes back, or whether a challenge page scores as -`blocked` or `captcha`. A browser loads one page at a time, which is why the -script runs several. Known misses: Zillow's home page scores as an empty search, -and Le Monde's front page leans paywall (0.71). +`blocked` or `captcha`. Each crawler drives its own session, and the browser +loads their pages in parallel. Known misses: Zillow's home page scores as an +empty search, and Le Monde's front page leans paywall (0.71). Runs from this checkout against a local browser build, like `classify_pages.py`: diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index 87c7a48..d0ac2e1 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -24,8 +24,8 @@ from lightpanda import AsyncBrowser, LightpandaError -# A browser loads one page at a time, so a crawl runs several. -BROWSERS = 6 +# Each crawler drives its own session: one browser loads their pages in parallel. +CRAWLERS = 6 URLS = [ # content @@ -163,12 +163,8 @@ async def main(): results, jev_times = [], [] start = perf_counter() - browsers = [AsyncBrowser() for _ in range(BROWSERS)] - try: - await asyncio.gather(*(b.start() for b in browsers)) - await asyncio.gather(*(crawl(b, queue, results, jev_times) for b in browsers)) - finally: - await asyncio.gather(*(b.close() for b in browsers)) + async with AsyncBrowser() as browser: + await asyncio.gather(*(crawl(browser, queue, results, jev_times) for _ in range(CRAWLERS))) elapsed = perf_counter() - start outcomes = Counter(result for result, _, _ in results) @@ -179,7 +175,7 @@ async def main(): print() print( - f"{len(results)} pages in {elapsed:.1f}s with {BROWSERS} browsers " + f"{len(results)} pages in {elapsed:.1f}s with {CRAWLERS} crawlers " f"({page_time:.1f}s of page time): {kept} kept, {len(results) - kept} skipped" ) print( From 7dd94412a6954f93f6d99fd412f6377861e5bbd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 15 Oct 2026 12:04:05 +0200 Subject: [PATCH 14/21] Simplify the triage crawl example visit() reads top to bottom: back off, accept cookies, wait. A semaphore caps the pages in flight instead of a queue and worker loop. --- examples/triage_crawl.py | 131 ++++++++++++++++++--------------------- 1 file changed, 62 insertions(+), 69 deletions(-) diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index d0ac2e1..07dc249 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -9,8 +9,8 @@ """Triage a crawl of real sites in parallel, and act on what Jev sees. Each page gets one ``page.judge()`` call: every wall check plus our own -questions. The verdict decides what happens next: accept a cookie wall and -look again, back off when the site says we are going too fast, wait for a +questions. The verdict decides what happens next: back off when the site +says we are going too fast, accept a cookie wall and look again, wait for a page that is still loading, or skip the page and say why. Needs TYPESAFE_API_KEY. Run: uv run examples/triage_crawl.py @@ -24,7 +24,7 @@ from lightpanda import AsyncBrowser, LightpandaError -# Each crawler drives its own session: one browser loads their pages in parallel. +# Pages loading at once, each in its own session of one browser. CRAWLERS = 6 URLS = [ @@ -75,6 +75,7 @@ ACCEPT = "/^(accept|aceptar|accepter|akzeptieren|agree|allow)/i" TTY = sys.stdout.isatty() +jev_times = [] def paint(text, color): @@ -82,106 +83,98 @@ def paint(text, color): return f"\033[{codes[color]}m{text}\033[0m" if TTY else text -def label(reason): - """is_empty_catalog -> empty catalog""" - return reason.removeprefix("is_").replace("_", " ") - - -async def judge(page, jev_times): +async def judge(page): start = perf_counter() verdict = await page.judge(questions=QUESTIONS) jev_times.append(perf_counter() - start) return verdict -async def accept_cookies(page): - """Click the wall's accept button. False when there is none to click.""" - found = await page.find_element(role="button", name=ACCEPT) - if not found: - return False - await page.click(backend_node_id=found[0]["backendNodeId"]) - # Banners fade out after the click. - await page.wait_for_state(state="networkidle") - return True +def rate_limited(verdict): + return verdict.answers["rate_limited"] >= 0.5 -async def visit(page, url, jev_times): +async def visit(page, url): """Load `url`, judge it, act on the verdict. Returns (verdict, actions).""" actions = [] await page.goto(url=url) - verdict = await judge(page, jev_times) - for _ in range(3): - if verdict.answers["rate_limited"] >= 0.5 and actions.count("backed off") < 2: - actions.append("backed off") - await asyncio.sleep(3 * actions.count("backed off")) - await page.goto(url=url) - elif verdict.is_consent_wall and "accepted cookies" not in actions and await accept_cookies(page): - actions.append("accepted cookies") - elif verdict.is_loading and "waited" not in actions: - actions.append("waited") - await page.wait_for_state(state="networkidle") - else: + verdict = await judge(page) + + for attempt in (1, 2): + if not rate_limited(verdict): break - verdict = await judge(page, jev_times) - return verdict, actions + actions.append("backed off") + await asyncio.sleep(3 * attempt) + await page.goto(url=url) + verdict = await judge(page) + + if verdict.is_consent_wall: + found = await page.find_element(role="button", name=ACCEPT) + if found: + actions.append("accepted cookies") + await page.click(backend_node_id=found[0]["backendNodeId"]) + await page.wait_for_state(state="networkidle") # banners fade out + verdict = await judge(page) + if verdict.is_loading: + actions.append("waited") + await page.wait_for_state(state="networkidle") + verdict = await judge(page) -def outcome(verdict): - """Either "kept" or why the page was skipped.""" - if verdict.answers["rate_limited"] >= 0.5: - return "rate limited" - return "kept" if verdict.ok else label(verdict.reason) + return verdict, actions -async def crawl(browser, queue, results, jev_times): - while not queue.empty(): - url = queue.get_nowait() - name = url.split("://", 1)[1][:44] +async def triage(browser, slots, url): + """Visit `url` once a slot is free, print a line, return (outcome, actions, seconds).""" + name = url.split("://", 1)[1][:44] + async with slots: start = perf_counter() - async with await browser.new_session() as page: - try: - verdict, actions = await visit(page, url, jev_times) - except LightpandaError as err: - print(f"{paint('fail', 'red')} {name:<44} {err}") - results.append(("failed", [], perf_counter() - start)) - continue + try: + async with await browser.new_session() as page: + verdict, actions = await visit(page, url) + except LightpandaError as err: + print(f"{paint('fail', 'red')} {name:<44} {err}") + return "failed", [], perf_counter() - start took = perf_counter() - start - acted = paint(f" <- {', '.join(actions)}", "yellow") if actions else "" - result = outcome(verdict) - if result == "kept": - line = f"{paint('keep', 'green')} {name:<44} {verdict.answers['kind']['choice']:<22}" - else: - line = f"{paint('skip', 'red')} {name:<44} {result:<22}" - print(f"{line} {paint(f'{took:.2f}s', 'dim')}{acted}") - results.append((result, actions, took)) + if rate_limited(verdict): + outcome = "rate limited" + elif verdict.ok: + outcome = "kept" + else: + outcome = verdict.reason.removeprefix("is_").replace("_", " ") # is_login_wall -> login wall + + if outcome == "kept": + line = f"{paint('keep', 'green')} {name:<44} {verdict.answers['kind']['choice']:<22}" + else: + line = f"{paint('skip', 'red')} {name:<44} {outcome:<22}" + acted = paint(f" <- {', '.join(actions)}", "yellow") if actions else "" + print(f"{line} {paint(f'{took:.2f}s', 'dim')}{acted}") + return outcome, actions, took -async def main(): - queue = asyncio.Queue() - for url in URLS: - queue.put_nowait(url) - results, jev_times = [], [] +async def main(): + slots = asyncio.Semaphore(CRAWLERS) start = perf_counter() async with AsyncBrowser() as browser: - await asyncio.gather(*(crawl(browser, queue, results, jev_times) for _ in range(CRAWLERS))) + results = await asyncio.gather(*(triage(browser, slots, url) for url in URLS)) elapsed = perf_counter() - start - outcomes = Counter(result for result, _, _ in results) + outcomes = Counter(outcome for outcome, _, _ in results) kept = outcomes.pop("kept", 0) acted = Counter(action for _, actions, _ in results for action in actions) page_time = sum(took for _, _, took in results) - jev_times.sort() print() print( f"{len(results)} pages in {elapsed:.1f}s with {CRAWLERS} crawlers " f"({page_time:.1f}s of page time): {kept} kept, {len(results) - kept} skipped" ) - print( - f"Jev: {len(jev_times)} calls, median {statistics.median(jev_times):.2f}s, " - f"p90 {jev_times[int(len(jev_times) * 0.9)]:.2f}s" - ) + if jev_times: + print( + f"Jev: {len(jev_times)} calls, median {statistics.median(jev_times):.2f}s, " + f"p90 {statistics.quantiles(jev_times, n=10)[-1]:.2f}s" + ) print("skipped: " + ", ".join(f"{reason} {n}" for reason, n in outcomes.most_common())) if acted: print("acted: " + ", ".join(f"{action} {n}" for action, n in acted.most_common())) From e806c6f6e65689aa7e5498782960e73e6cf3f847 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 15 Oct 2026 12:47:12 +0200 Subject: [PATCH 15/21] Print every verdict in the triage crawl example A verdict the crawler acts on gets its own retry line saying what it does, so a cookie wall shows before the page behind it and a rate-limited page shows once per try. The cookie click uses found[0].click(). --- examples/README.md | 88 ++++++++++++++++++++++------------------ examples/triage_crawl.py | 55 +++++++++++++++---------- 2 files changed, 81 insertions(+), 62 deletions(-) diff --git a/examples/README.md b/examples/README.md index 522b884..8c6e965 100644 --- a/examples/README.md +++ b/examples/README.md @@ -262,10 +262,10 @@ LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages. ## `triage_crawl.py` — crawl real sites in parallel and act on what Jev sees The same `judge()` call over 29 real pages, six at a time in one browser. The -verdict decides what the crawler does next: accept a cookie wall and look -again, back off when the site says we are going too fast, wait for a page -that is still loading, or skip the page and say why. "Too fast" is our own -question, asked in the same call as the wall checks: +verdict decides what the crawler does next: back off when the site says we are +going too fast, accept a cookie wall, wait for a page that is still loading, +and then look again; or keep the page, or skip it and say why. "Too fast" is +our own question, asked in the same call as the wall checks: ```python QUESTIONS = { @@ -279,47 +279,55 @@ if verdict.answers["rate_limited"] >= 0.5: await asyncio.sleep(3) # and load it again elif verdict.is_consent_wall: found = await page.find_element(role="button", name="/^(accept|aceptar|akzeptieren)/i") - await page.click(backend_node_id=found[0]["backendNodeId"]) + await found[0].click() ``` +Every verdict prints a line. One the crawler acts on says `retry` and what it +does about it, and the page's last verdict says `keep` or `skip`, so Indeed +shows up twice and a rate-limited page once per try: + ``` -keep docs.python.org/3/library/asyncio.html docs 0.73s -keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.95s -keep en.wikipedia.org/wiki/Web_scraping article 1.03s -keep en.wikipedia.org/wiki/Headless_browser article 1.04s -keep quotes.toscrape.com/js/ listing 1.17s -keep books.toscrape.com/catalogue/a-light-in-the- product 1.28s -keep lobste.rs/ listing 0.85s -keep www.spiegel.de/ listing 1.60s -keep github.com/lightpanda-io/browser listing 2.54s -skip github.com/settings/profile login wall 1.14s -keep www.indeed.com/ search 2.84s <- accepted cookies -skip www.g2.com/ blocked 0.42s -skip www.wsj.com/ blocked 0.41s -skip www.linkedin.com/feed/ login wall 1.49s -skip www.economist.com/leaders/2024/01/04/what-to blocked 0.60s -skip www.zeit.de/index error page 0.38s -skip stackoverflow.com/questions/231767/what-does blocked 0.43s -keep pypi.org/project/lightpanda/ listing 0.77s -keep news.ycombinator.com/ listing 4.54s <- backed off -keep news.ycombinator.com/newest listing 4.90s <- backed off -skip news.ycombinator.com/login login wall 4.30s <- backed off -skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 0.98s -skip web.whatsapp.com/ unsupported browser 1.12s -skip arxiv.org/abs/1706.03762 error page 0.29s -skip www.python.org/no-such-page error page 0.66s -skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.57s -skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.74s -skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.63s -skip github.com/lightpanda-io/does-not-exist error page 1.85s - -29 pages in 8.2s with 6 crawlers (42.3s of page time): 13 kept, 16 skipped -Jev: 33 calls, median 0.22s, p90 0.48s -skipped: error page 5, blocked 4, login wall 3, empty catalog 3, unsupported browser 1 -acted: backed off 3, accepted cookies 1 +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.63s +keep docs.python.org/3/library/asyncio.html docs 0.65s +keep en.wikipedia.org/wiki/Headless_browser article 0.73s +keep quotes.toscrape.com/js/ listing 1.06s +keep en.wikipedia.org/wiki/Web_scraping article 1.08s +keep books.toscrape.com/catalogue/a-light-in-the- product 1.31s +keep lobste.rs/ listing 0.91s +keep www.spiegel.de/ listing 1.15s +retry news.ycombinator.com/ rate limited 1.11s -> back off 3s +retry news.ycombinator.com/newest rate limited 1.12s -> back off 3s +skip news.ycombinator.com/login login wall 0.75s +keep github.com/lightpanda-io/browser docs 2.03s +retry www.indeed.com/ consent wall 1.59s -> accept cookies +skip www.g2.com/ captcha 0.32s +skip github.com/settings/profile login wall 1.13s +skip www.wsj.com/ captcha 0.41s +skip www.linkedin.com/feed/ login wall 1.15s +skip www.economist.com/leaders/2024/01/04/what-to captcha 0.59s +skip stackoverflow.com/questions/231767/what-does blocked 0.37s +skip www.zeit.de/index error page 0.37s +keep www.indeed.com/ search 3.09s +skip www.npmjs.com/search?q=xqzzzvqkplorbt blocked 0.55s +keep pypi.org/project/lightpanda/ listing 1.20s +skip web.whatsapp.com/ unsupported browser 0.82s +skip www.python.org/no-such-page error page 0.88s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.06s +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.27s +keep news.ycombinator.com/newest listing 4.72s +skip arxiv.org/abs/1706.03762 error page 0.35s +retry news.ycombinator.com/ rate limited 4.80s -> back off 6s +skip github.com/lightpanda-io/does-not-exist error page 1.25s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.63s +keep news.ycombinator.com/ listing 11.48s + +29 pages in 12.7s with 6 crawlers (42.1s of page time): 13 kept, 16 skipped +Jev: 33 calls, median 0.22s, p90 0.29s +skipped: error page 5, login wall 3, captcha 3, blocked 2, empty catalog 2, unsupported browser 1 +acted: back off 3, accept cookies 1 ``` -What the skipped pages actually showed: Indeed's cookie wall is in Spanish, +What the walls actually showed: Indeed's cookie wall is in Spanish, Zeit's is a German notice that it reserves its content against data mining, arXiv's is a bare Varnish 403, eBay's is "Something went wrong on our end", and Stack Overflow's is empty. Hacker News rate-limits diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index 07dc249..e7dadbe 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -94,16 +94,40 @@ def rate_limited(verdict): return verdict.answers["rate_limited"] >= 0.5 +def describe(verdict): + """The page's kind when it is worth reading, else why not.""" + if rate_limited(verdict): + return "rate limited" + if verdict.ok: + return verdict.answers["kind"]["choice"] + return verdict.reason.removeprefix("is_").replace("_", " ") # is_login_wall -> login wall + + async def visit(page, url): - """Load `url`, judge it, act on the verdict. Returns (verdict, actions).""" + """Load `url` and act on what Jev sees, printing a line per verdict. + Returns the last verdict and the actions taken.""" + name = url.split("://", 1)[1][:44] + start = perf_counter() actions = [] + + def show(verdict, action=None, detail=""): + if action: + actions.append(action) + status, note = paint("retry", "yellow"), paint(f" -> {action}{detail}", "yellow") + elif verdict.ok and not rate_limited(verdict): + status, note = paint("keep ", "green"), "" + else: + status, note = paint("skip ", "red"), "" + took = paint(f"{perf_counter() - start:.2f}s", "dim") + print(f"{status} {name:<44} {describe(verdict):<22} {took}{note}") + await page.goto(url=url) verdict = await judge(page) for attempt in (1, 2): if not rate_limited(verdict): break - actions.append("backed off") + show(verdict, "back off", f" {3 * attempt}s") await asyncio.sleep(3 * attempt) await page.goto(url=url) verdict = await judge(page) @@ -111,45 +135,32 @@ async def visit(page, url): if verdict.is_consent_wall: found = await page.find_element(role="button", name=ACCEPT) if found: - actions.append("accepted cookies") - await page.click(backend_node_id=found[0]["backendNodeId"]) + show(verdict, "accept cookies") + await found[0].click() await page.wait_for_state(state="networkidle") # banners fade out verdict = await judge(page) if verdict.is_loading: - actions.append("waited") + show(verdict, "wait") await page.wait_for_state(state="networkidle") verdict = await judge(page) + show(verdict) return verdict, actions async def triage(browser, slots, url): - """Visit `url` once a slot is free, print a line, return (outcome, actions, seconds).""" - name = url.split("://", 1)[1][:44] + """Visit `url` once a slot is free. Returns (outcome, actions, seconds).""" async with slots: start = perf_counter() try: async with await browser.new_session() as page: verdict, actions = await visit(page, url) except LightpandaError as err: - print(f"{paint('fail', 'red')} {name:<44} {err}") + print(f"{paint('fail ', 'red')} {url.split('://', 1)[1][:44]:<44} {err}") return "failed", [], perf_counter() - start took = perf_counter() - start - - if rate_limited(verdict): - outcome = "rate limited" - elif verdict.ok: - outcome = "kept" - else: - outcome = verdict.reason.removeprefix("is_").replace("_", " ") # is_login_wall -> login wall - - if outcome == "kept": - line = f"{paint('keep', 'green')} {name:<44} {verdict.answers['kind']['choice']:<22}" - else: - line = f"{paint('skip', 'red')} {name:<44} {outcome:<22}" - acted = paint(f" <- {', '.join(actions)}", "yellow") if actions else "" - print(f"{line} {paint(f'{took:.2f}s', 'dim')}{acted}") + outcome = "kept" if verdict.ok and not rate_limited(verdict) else describe(verdict) return outcome, actions, took From 758da0d95b159097b833f289e565a84471d166b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 15 Oct 2026 13:54:48 +0200 Subject: [PATCH 16/21] Show cookie walls the triage crawl can accept Indeed now answers with a 403 bot block on most loads, so the crawl never reached its cookie wall. El Mundo and 20 Minutes serve one on every load, and clicking its accept button clears it. --- examples/README.md | 93 ++++++++++++++++++++-------------------- examples/triage_crawl.py | 3 +- 2 files changed, 49 insertions(+), 47 deletions(-) diff --git a/examples/README.md b/examples/README.md index 8c6e965..1329bb9 100644 --- a/examples/README.md +++ b/examples/README.md @@ -261,7 +261,7 @@ LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages. ## `triage_crawl.py` — crawl real sites in parallel and act on what Jev sees -The same `judge()` call over 29 real pages, six at a time in one browser. The +The same `judge()` call over 30 real pages, six at a time in one browser. The verdict decides what the crawler does next: back off when the site says we are going too fast, accept a cookie wall, wait for a page that is still loading, and then look again; or keep the page, or skip it and say why. "Too fast" is @@ -283,55 +283,56 @@ elif verdict.is_consent_wall: ``` Every verdict prints a line. One the crawler acts on says `retry` and what it -does about it, and the page's last verdict says `keep` or `skip`, so Indeed -shows up twice and a rate-limited page once per try: +does about it, and the page's last verdict says `keep` or `skip`, so the two +cookie walls show up twice and a rate-limited page once per try: ``` -keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.63s -keep docs.python.org/3/library/asyncio.html docs 0.65s -keep en.wikipedia.org/wiki/Headless_browser article 0.73s -keep quotes.toscrape.com/js/ listing 1.06s -keep en.wikipedia.org/wiki/Web_scraping article 1.08s -keep books.toscrape.com/catalogue/a-light-in-the- product 1.31s -keep lobste.rs/ listing 0.91s -keep www.spiegel.de/ listing 1.15s -retry news.ycombinator.com/ rate limited 1.11s -> back off 3s -retry news.ycombinator.com/newest rate limited 1.12s -> back off 3s -skip news.ycombinator.com/login login wall 0.75s -keep github.com/lightpanda-io/browser docs 2.03s -retry www.indeed.com/ consent wall 1.59s -> accept cookies -skip www.g2.com/ captcha 0.32s -skip github.com/settings/profile login wall 1.13s -skip www.wsj.com/ captcha 0.41s -skip www.linkedin.com/feed/ login wall 1.15s -skip www.economist.com/leaders/2024/01/04/what-to captcha 0.59s -skip stackoverflow.com/questions/231767/what-does blocked 0.37s -skip www.zeit.de/index error page 0.37s -keep www.indeed.com/ search 3.09s -skip www.npmjs.com/search?q=xqzzzvqkplorbt blocked 0.55s -keep pypi.org/project/lightpanda/ listing 1.20s -skip web.whatsapp.com/ unsupported browser 0.82s -skip www.python.org/no-such-page error page 0.88s -skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.06s -skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.27s -keep news.ycombinator.com/newest listing 4.72s -skip arxiv.org/abs/1706.03762 error page 0.35s -retry news.ycombinator.com/ rate limited 4.80s -> back off 6s -skip github.com/lightpanda-io/does-not-exist error page 1.25s -skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.63s -keep news.ycombinator.com/ listing 11.48s - -29 pages in 12.7s with 6 crawlers (42.1s of page time): 13 kept, 16 skipped -Jev: 33 calls, median 0.22s, p90 0.29s -skipped: error page 5, login wall 3, captcha 3, blocked 2, empty catalog 2, unsupported browser 1 -acted: back off 3, accept cookies 1 +keep docs.python.org/3/library/asyncio.html docs 0.47s +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.69s +keep en.wikipedia.org/wiki/Headless_browser article 0.71s +keep en.wikipedia.org/wiki/Web_scraping article 0.93s +keep quotes.toscrape.com/js/ listing 1.00s +keep books.toscrape.com/catalogue/a-light-in-the- product 1.24s +keep lobste.rs/ listing 1.12s +keep www.spiegel.de/ listing 1.21s +keep github.com/lightpanda-io/browser listing 1.60s +keep news.ycombinator.com/ listing 1.15s +keep news.ycombinator.com/newest listing 1.31s +skip www.g2.com/ blocked 0.35s +retry news.ycombinator.com/login rate limited 0.98s -> back off 3s +skip github.com/settings/profile login wall 1.01s +retry www.20minutes.fr/ consent wall 1.33s -> accept cookies +skip www.wsj.com/ captcha 0.59s +skip www.economist.com/leaders/2024/01/04/what-to blocked 0.39s +skip www.linkedin.com/feed/ login wall 1.61s +skip stackoverflow.com/questions/231767/what-does blocked 0.49s +skip pypi.org/project/lightpanda/ captcha 0.74s +skip www.zeit.de/index error page 0.35s +retry www.elmundo.es/ consent wall 3.01s -> accept cookies +skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 1.02s +skip web.whatsapp.com/ unsupported browser 1.07s +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.59s +skip www.python.org/no-such-page error page 0.94s +skip news.ycombinator.com/login login wall 4.36s +skip arxiv.org/abs/1706.03762 error page 0.40s +keep www.elmundo.es/ other 5.23s +skip github.com/lightpanda-io/does-not-exist error page 0.92s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.55s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.60s +keep www.20minutes.fr/ other 6.11s + +30 pages in 10.1s with 6 crawlers (41.0s of page time): 13 kept, 17 skipped +Jev: 33 calls, median 0.22s, p90 0.30s +skipped: error page 5, login wall 3, blocked 3, empty catalog 3, captcha 2, unsupported browser 1 +acted: accept cookies 2, back off 1 ``` -What the walls actually showed: Indeed's cookie wall is in Spanish, -Zeit's is a German notice that it reserves its content against data mining, -arXiv's is a bare Varnish 403, eBay's is "Something -went wrong on our end", and Stack Overflow's is empty. Hacker News rate-limits -three tabs opened at once, and says so in a sentence the crawler had no rule for. +What the walls actually showed: El Mundo's and 20 Minutes' cookie walls are +popups over the front page that one click on the accept button clears, Zeit's +is a German notice that it reserves its content against data mining, arXiv's +is a bare Varnish 403, eBay's is "Something went wrong on our end", and Stack +Overflow's is empty. Hacker News rate-limits three tabs opened at once, and +says so in a sentence the crawler had no rule for. Sites change and the model is not deterministic, so a run differs a little: how often Hacker News pushes back, or whether a challenge page scores as diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index e7dadbe..46a0f73 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -41,7 +41,8 @@ "https://news.ycombinator.com/", "https://news.ycombinator.com/newest", # a cookie wall in front of the content - "https://www.indeed.com/", + "https://www.elmundo.es/", + "https://www.20minutes.fr/", # walls "https://news.ycombinator.com/login", "https://github.com/settings/profile", From 27510fc32ea6e1fd8365c42ad7c528da5ed6a9c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Thu, 22 Oct 2026 23:28:04 +0200 Subject: [PATCH 17/21] Judge a 4xx or 5xx page by its status, without asking Jev Of the 1,781 pages that answered 4xx or 5xx in the classifier's crawl, Jev found none worth reading: every one fired a check, and the seven that fired none on both votes were blocks it scored near 0.6. Asking it is a round trip for an answer the status already gave. The session keeps the status the last navigation or action reported, and judge() returns from it before calling classify: 401 names a login wall, 402 a paywall, 403 and 429 a block, anything else an error page. Scores and answers stay None, so a caller can tell a verdict the model gave from one it did not. A 2xx page still goes to Jev, since bot blocks often arrive as 200. --- lightpanda/browser.py | 31 +++++++++++++++++++++++++++++++ tests/test_classify.py | 17 +++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lightpanda/browser.py b/lightpanda/browser.py index d7b15d2..61ae108 100644 --- a/lightpanda/browser.py +++ b/lightpanda/browser.py @@ -84,6 +84,10 @@ class PageVerdict: Questions passed to :meth:`Session.judge` are asked in the same call, and their answers land in :attr:`answers`. + + A page that answered 4xx or 5xx is judged by its status alone, without + asking the model: :attr:`http_status` holds it, the check it names is + true, and every score and answer is None. """ is_blocked: bool @@ -112,6 +116,9 @@ class PageVerdict: """The answers to the questions passed to :meth:`Session.judge`, keyed as asked and shaped as :meth:`Session.classify` returns them. Empty when none were passed.""" + http_status: int | None + """The 4xx or 5xx status that decided the verdict without the model, or + None when the model was asked.""" def __init__(self, answers: dict, threshold: float, asked: Iterable[str] = ()): asked = set(asked) @@ -119,6 +126,15 @@ def __init__(self, answers: dict, threshold: float, asked: Iterable[str] = ()): self.scores = {_snake(preset): score for preset, score in answers.items() if preset not in asked} for attr, score in self.scores.items(): setattr(self, attr, score is not None and score >= threshold) + self.http_status = None + + @classmethod + def _from_status(cls, http_status: int, asked: Iterable[str]) -> PageVerdict: + checks = [attr for attr, kind in cls.__annotations__.items() if kind == "bool"] + verdict = cls(dict.fromkeys([*checks, *asked]), 0.5, asked) + verdict.http_status = http_status + setattr(verdict, _STATUS_CHECKS.get(http_status, "is_error_page"), True) + return verdict @property def ok(self) -> bool: @@ -137,6 +153,12 @@ def __repr__(self) -> str: return f"PageVerdict({fired})" +# Of 1,781 pages that answered 4xx or 5xx in the classifier's crawl, the model +# found none worth reading, so judge() skips them without asking it. The +# statuses that say why name their check; any other names an error page. +_STATUS_CHECKS = {401: "is_login_wall", 402: "is_paywall", 403: "is_blocked", 429: "is_blocked"} + + def _snake(name: str) -> str: return re.sub(r"(? Pag print(verdict.answers["has_price"]) # 0.99 ``` + A page that answered 4xx or 5xx is not worth reading whatever it says, + so its verdict comes from the status and the model is not asked; see + :attr:`PageVerdict.http_status`. + Args: questions: Questions in the object form :meth:`classify` takes. threshold: The probability at which a check counts as true. """ + if self._http_status is not None and self._http_status >= 400: + return PageVerdict._from_status(self._http_status, asked=questions or ()) if not questions: # An empty questions object asks the browser for every preset. return PageVerdict(self.call("classify", questions={}), threshold) diff --git a/tests/test_classify.py b/tests/test_classify.py index 4bd815a..37827a0 100644 --- a/tests/test_classify.py +++ b/tests/test_classify.py @@ -124,6 +124,23 @@ def test_judge_with_questions(classify_browser, fixture_url): assert verdict.is_login_wall and not verdict.ok +def test_judge_error_status_skips_the_model(classify_browser, fixture_url): + with classify_browser.new_session() as page: + page.goto(url=f"{fixture_url}/missing.html") + verdict = page.judge(questions={"has_price": "Does the page show a price?"}) + assert verdict.http_status == 404 + assert verdict.is_error_page and not verdict.is_paywall and not verdict.ok + assert verdict.reason == "is_error_page" + # The mock answers 0.9 to everything, so None means it was never asked. + assert set(verdict.scores.values()) == {None} + assert verdict.answers == {"has_price": None} + + page.goto(url=f"{fixture_url}/index.html") + verdict = page.judge() + assert verdict.http_status is None + assert set(verdict.scores.values()) == {0.9} + + async def test_judge_async(classify_browser, fixture_url): from lightpanda import AsyncBrowser From d2660b4a4c1884deb089b8413a8cb53248f2666f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Mon, 2 Nov 2026 18:23:58 +0100 Subject: [PATCH 18/21] Run the classify examples against the published package --- examples/classify_pages.py | 4 ---- examples/triage_crawl.py | 4 ---- 2 files changed, 8 deletions(-) diff --git a/examples/classify_pages.py b/examples/classify_pages.py index eed6edc..f7c7272 100644 --- a/examples/classify_pages.py +++ b/examples/classify_pages.py @@ -1,10 +1,6 @@ # /// script # requires-python = ">=3.10" # dependencies = ["lightpanda"] -# -# # judge() is not on PyPI yet: use this checkout until it is. -# [tool.uv.sources] -# lightpanda = { path = "..", editable = true } # /// """Triage a crawl: ``page.judge()`` says whether each page is a wall, a CAPTCHA or an empty search, and answers your own questions in the same call. diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index 46a0f73..9b37db5 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -1,10 +1,6 @@ # /// script # requires-python = ">=3.10" # dependencies = ["lightpanda"] -# -# # judge() is not on PyPI yet: use this checkout until it is. -# [tool.uv.sources] -# lightpanda = { path = "..", editable = true } # /// """Triage a crawl of real sites in parallel, and act on what Jev sees. From 4af9191d4ed94f03bd70b3d158e266aebd24bfcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Mon, 2 Nov 2026 18:23:58 +0100 Subject: [PATCH 19/21] Regenerate _methods.py against nightly --- lightpanda/_methods.py | 122 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 112 insertions(+), 10 deletions(-) diff --git a/lightpanda/_methods.py b/lightpanda/_methods.py index 7219494..c4cb1bd 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -20,6 +20,22 @@ class SessionMethods: def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError + def accept_cookies(self, *, prefer: str | None = None, selectors: list | None = None) -> Any: + """Dismiss the cookie consent banner on the current page: the browser offers the banner's own controls to TypeSafe System One (Jev), clicks the one it picks, and re-reads the page to check the banner went. Returns JSON — `dismissed` is what was clicked, `verified` whether the page agreed afterwards, `selectors` the controls clicked in order, and `reason` why nothing happened when nothing did. A click that leaves a banner up (a confirmation, say) is followed by one more pick. A page with nothing to click costs no model call; passing `selectors` clicks them in order and asks nothing, which is how a recorded call replays. Otherwise needs TYPESAFE_API_KEY. + + Args: + prefer: Whether to accept the cookies or refuse all non-essential ones. Defaults to 'accept'. + selectors: Optional CSS selectors of the controls to click in order, from an earlier call's result. Clicked without asking the model; one that is not on the page stops the clicking there. + """ + return self.call("acceptCookies", prefer=prefer, selectors=selectors) + def call_page_tool(self, *, name: str, arguments: dict | None = None) -> Any: + """Call a WebMCP tool the current page registered (see `pageTools`) and return its result: the text of an MCP-style `content` array, or JSON for any other value. A tool that throws or rejects reports its error. The tool runs the site's own code and may change the page or act on the user's account, so treat a tool without `readOnlyHint` like a form submit. + + Args: + name: Tool name, as `pageTools` lists it. + arguments: Optional. The tool's input, matching its `inputSchema`. Defaults to {}. + """ + return self.call("callPageTool", name=name, arguments=arguments) def classify(self, *, questions: str | dict | list, selector: str | None = None, presets: bool | None = None) -> Any: """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. @@ -55,6 +71,14 @@ def detect_forms(self, *, url: str | None = None, timeout: int | None = None) -> timeout: Optional timeout in milliseconds. Defaults to 10000. """ return self.call("detectForms", url=url, timeout=timeout) + def download(self, *, url: str, path: str) -> Any: + """Fetch a URL and save the response body to a local file, sending the session's cookies so authenticated sites work. The way to get a binary or large document (PDF, spreadsheet, archive) out of the browser. Nothing is saved unless the status is 200-203 (like Chrome), and a failed download leaves an existing file at `path` untouched. Requires a loaded page — it fails before the first `goto`. + + Args: + url: Absolute http(s) URL to fetch. + path: Relative path (no '..' segments) to save the response body to. Created or overwritten. The response reports the absolute location. + """ + return self.call("download", url=url, path=path) def evaluate(self, *, script: str, url: str | None = None, timeout: int | None = None, save: str | None = None) -> Any: """Evaluate JavaScript in the current page context — an escape hatch for page-side logic the dedicated tools can't express; prefer `extract` for data and click/fill/etc. for actions. It runs in the page, so it cannot see the agent script's variables or builtins — interpolate any value into the `script` string. A bare trailing expression yields its value; top-level `await` and `return` are supported (the body then runs as an async function, so use `return` to produce a value). Objects and arrays return as JSON, so no `JSON.stringify` is needed. If a url is provided, it navigates there first. The `globalThis.lp` object exposes a Session-scoped bridge store: values written via `lp.foo = ...` auto-sync at end of evaluate, surviving navigation; values previously set via `/extract save=` or `/evaluate save=` appear as `lp.`. @@ -194,7 +218,20 @@ def links(self, *, limit: int | None = None, url: str | None = None, timeout: in timeout: Optional timeout in milliseconds. Defaults to 10000. """ return self.call("links", limit=limit, url=url, timeout=timeout) - def markdown(self, *, selector: str | None = None, backend_node_id: int | None = None, max_bytes: int | None = None, strip: dict | None = None, url: str | None = None, timeout: int | None = None) -> Any: + def login(self, *, password: str, username: str | None = None, username_selector: str | None = None, password_selector: str | None = None, submit_selector: str | None = None, next_selector: str | None = None, decide_only: bool | None = None) -> Any: + """Sign in on the current page. The browser collects the candidate fields and sign-in controls, asks TypeSafe System One (Jev) only what the markup leaves ambiguous, fills the credentials, submits, and re-reads the page to say whether it worked. A password is only ever typed into an `input[type=password]`, and credentials only go to an https (or loopback) page whose form posts to an https URL. Pass `$LP_*` placeholders rather than literal secrets: they resolve inside the browser and never appear in the result. Returns JSON with the selectors it used, so a recorded call replays them with no model call. Otherwise needs TYPESAFE_API_KEY. + + Args: + password: The password, as a $LP_* placeholder. + username: The username, email or other identifier, as a $LP_* placeholder. Omit on a page that asks only for the password. + username_selector: Optional CSS selector of the identifier field, from an earlier call's result. Given with passwordSelector, the fields are filled with no model call. + password_selector: Optional CSS selector of the password field, from an earlier call's result. Must name an input[type=password]. + submit_selector: Optional CSS selector of the control that submits the form. Without it, Enter is pressed in the filled field. + next_selector: Optional CSS selector of the control that submits the username on a page that asks for the password on a later step. Without it, Enter is pressed in the username field. + decide_only: Report which fields would be used and type nothing. For checking the picks on a page without sending credentials. + """ + return self.call("login", password=password, username=username, username_selector=username_selector, password_selector=password_selector, submit_selector=submit_selector, next_selector=next_selector, decide_only=decide_only) + def markdown(self, *, selector: str | None = None, backend_node_id: int | None = None, max_bytes: int | None = None, strip: dict | None = None, url: str | None = None, alternate: bool | None = None, timeout: int | None = None) -> Any: """Render the page (or a subtree) as markdown. Scope with `selector` or `backendNodeId` to read just the relevant region — full-page markdown is the last resort. Use `maxBytes` to cap long pages. Args: @@ -203,9 +240,10 @@ def markdown(self, *, selector: str | None = None, backend_node_id: int | None = max_bytes: Optional soft cap on output size in bytes. Content is truncated at a UTF-8 boundary and a short '[truncated]' marker is appended past the cap. strip: Optional. Omit element groups from the output; same groups as the html tool's strip. `shell` (page chrome by markup) and `clutter` (keep only the main content, in the manner of reader modes) are the ones that matter for reading; `ui` also drops images. url: Optional URL to navigate to before rendering. An empty string is treated as omitted. + alternate: Optional. When the page links a markdown version of itself (), return that file instead of converting the page. It is the author's file and can differ from the rendered page; the output then starts with a comment naming its URL, which maxBytes does not count. Falls back to the page when there is no such link, the page itself failed to load (HTTP error status or bot challenge), or the alternate does not load as markdown within what is left of the timeout. Cannot be combined with selector or backendNodeId. Defaults to false. timeout: Optional timeout in milliseconds. Defaults to 10000. """ - return self.call("markdown", selector=selector, backend_node_id=backend_node_id, max_bytes=max_bytes, strip=strip, url=url, timeout=timeout) + return self.call("markdown", selector=selector, backend_node_id=backend_node_id, max_bytes=max_bytes, strip=strip, url=url, alternate=alternate, timeout=timeout) def node_details(self, *, backend_node_id: int) -> Any: """Details for a node by backendNodeId: a ready-to-use CSS `selector` that resolves to the node (the first match, as click/fill resolve it), plus tag, role, name, interactivity, disabled, value, input type, placeholder, href, id, class, checked, select options. The canonical way to turn a tree backendNodeId into a CSS selector. @@ -213,6 +251,9 @@ def node_details(self, *, backend_node_id: int) -> Any: backend_node_id: The backend node ID of the element to inspect. """ return self.call("nodeDetails", backend_node_id=backend_node_id) + def page_tools(self) -> Any: + """List the tools the current page registers for agents through WebMCP (`navigator.modelContext.registerTool`), as JSON with each tool's `name`, `description`, `inputSchema` and hints. A page tool runs the site's own code and can be more reliable than driving its UI; call one with `callPageTool`. Many pages register their tools after `load`: if the list is empty on a page you expect to have tools, call `waitForState` with `networkidle` and list again.""" + return self.call("pageTools") def press(self, *, key: str, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Press a keyboard key, dispatching keydown and keyup events. Use key names like 'Enter', 'Tab', 'Escape', 'ArrowDown', 'Backspace', or single characters like 'a', '1'. Common shorthand is normalized: 'enter'/'return' → 'Enter', 'esc' → 'Escape', 'up'/'down'/'left'/'right' → 'Arrow*', 'space' → ' '. Pressing 'Enter' on a form input or submit button triggers implicit form submission. @@ -229,6 +270,15 @@ def press(self, *, key: str, selector: str | None = None, backend_node_id: int | - `title`: Document title. Empty or absent when the page has none. """ return self.call("press", key=key, selector=selector, backend_node_id=backend_node_id) + def run(self, *, script: str | None = None, path: str | None = None, timeout: int | None = None) -> Any: + """Run a Lightpanda agent script in this session, as `lightpanda run` does, and return its console output followed by the value it returns. Pass the source as `script`, or the `path` of a file `save` wrote. The script drives pages through `const page = new Page(); await page.goto(url);` and the builtins as methods on `page`; `$LP_*` placeholders are resolved. Pages the script opens are closed when it ends; cookies and storage stay in the session, so a login carries over to the next call. Script variables do not carry over. A thrown error, a failed step or the timeout ends the script and is reported as an error after the output so far. + + Args: + script: The agent script source, as `save` writes it or `lightpanda run` takes it. Pass this or `path`. + path: A script file to run instead of `script`, such as one `save` wrote. Relative to the server's working directory. + timeout: Optional. Milliseconds before the script is stopped and reported as an error with its output so far. At least 1; defaults to 60000. + """ + return self.call("run", script=script, path=path, timeout=timeout) def screenshot(self, *, path: str | None = None, selector: str | None = None, backend_node_id: int | None = None, full_page: bool | None = None, strip: dict | None = None, url: str | None = None, timeout: int | None = None) -> Any: """Render the page, or one node, as a PNG: the text layout Lightpanda computes, not a pixel-accurate browser rendering (no images, fonts or CSS colours). With `path`, writes the file at full size and returns its location; without it, returns the image inline where the client can display one, at most 1280px wide and 4096px tall. Use it to see spatial layout; read content with `markdown`/`tree`. @@ -260,7 +310,7 @@ def scroll(self, *, selector: str | None = None, backend_node_id: int | None = N """ return self.call("scroll", selector=selector, backend_node_id=backend_node_id, x=x, y=y) def search(self, *, query: str, timeout: int | None = None) -> Any: - """Run a web search and return results as markdown: a numbered list of {title, url, snippet}. Search tries brave, tavily, exa, then keenable in order, each when its API key (BRAVE_API_KEY, TAVILY_API_KEY, EXA_API_KEY or KEENABLE_API_KEY) is set; keenable also works without a key through its public endpoint (rate-limited per client IP). Prefer this over goto-ing google.com/search directly (Google blocks the browser on User-Agent/TLS). The browser does not navigate — to open a result, use `goto` with its URL. + """Run a web search and return results as markdown: a numbered list of {title, url, snippet}. Search tries brave, tavily, exa, parallel, then keenable in order, each when its API key (BRAVE_API_KEY, TAVILY_API_KEY, EXA_API_KEY, PARALLEL_API_KEY or KEENABLE_API_KEY) is set; keenable also works without a key through its public endpoint (rate-limited per client IP). Prefer this over goto-ing google.com/search directly (Google blocks the browser on User-Agent/TLS). The browser does not navigate — to open a result, use `goto` with its URL. Args: query: The search query. @@ -391,14 +441,15 @@ def html(self, *, max_bytes: int | None = None, strip: dict | None = None) -> An strip: Optional. Omit element groups from the output: `js` (script, noscript, script preloads), `css` (style, stylesheet links), `ui` (css plus img, picture, video, audio, svg, canvas, iframe), `invisible` (elements an author rule or inline style sets to display:none), `shell` (nav, aside, dialog, page-level header/footer and the matching landmark roles; skipped when that would drop most of the text), `clutter` (keep only the main content, in the manner of reader modes; includes `shell` and `invisible`, and falls back to `shell` when it finds too little). {"js":true,"css":true} keeps a page dump small. """ return self.call("html", max_bytes=max_bytes, strip=strip) - def markdown(self, *, max_bytes: int | None = None, strip: dict | None = None) -> Any: + def markdown(self, *, max_bytes: int | None = None, strip: dict | None = None, alternate: bool | None = None) -> Any: """Render the page (or a subtree) as markdown. Scope with `selector` or `backendNodeId` to read just the relevant region — full-page markdown is the last resort. Use `maxBytes` to cap long pages. Args: max_bytes: Optional soft cap on output size in bytes. Content is truncated at a UTF-8 boundary and a short '[truncated]' marker is appended past the cap. strip: Optional. Omit element groups from the output; same groups as the html tool's strip. `shell` (page chrome by markup) and `clutter` (keep only the main content, in the manner of reader modes) are the ones that matter for reading; `ui` also drops images. + alternate: Optional. When the page links a markdown version of itself (), return that file instead of converting the page. It is the author's file and can differ from the rendered page; the output then starts with a comment naming its URL, which maxBytes does not count. Falls back to the page when there is no such link, the page itself failed to load (HTTP error status or bot challenge), or the alternate does not load as markdown within what is left of the timeout. Cannot be combined with selector or backendNodeId. Defaults to false. """ - return self.call("markdown", max_bytes=max_bytes, strip=strip) + return self.call("markdown", max_bytes=max_bytes, strip=strip, alternate=alternate) def node_details(self) -> Any: """Details for a node by backendNodeId: a ready-to-use CSS `selector` that resolves to the node (the first match, as click/fill resolve it), plus tag, role, name, interactivity, disabled, value, input type, placeholder, href, id, class, checked, select options. The canonical way to turn a tree backendNodeId into a CSS selector.""" return self.call("nodeDetails") @@ -481,6 +532,22 @@ class AsyncSessionMethods: async def call(self, tool: str, **kwargs: Any) -> Any: raise NotImplementedError + async def accept_cookies(self, *, prefer: str | None = None, selectors: list | None = None) -> Any: + """Dismiss the cookie consent banner on the current page: the browser offers the banner's own controls to TypeSafe System One (Jev), clicks the one it picks, and re-reads the page to check the banner went. Returns JSON — `dismissed` is what was clicked, `verified` whether the page agreed afterwards, `selectors` the controls clicked in order, and `reason` why nothing happened when nothing did. A click that leaves a banner up (a confirmation, say) is followed by one more pick. A page with nothing to click costs no model call; passing `selectors` clicks them in order and asks nothing, which is how a recorded call replays. Otherwise needs TYPESAFE_API_KEY. + + Args: + prefer: Whether to accept the cookies or refuse all non-essential ones. Defaults to 'accept'. + selectors: Optional CSS selectors of the controls to click in order, from an earlier call's result. Clicked without asking the model; one that is not on the page stops the clicking there. + """ + return await self.call("acceptCookies", prefer=prefer, selectors=selectors) + async def call_page_tool(self, *, name: str, arguments: dict | None = None) -> Any: + """Call a WebMCP tool the current page registered (see `pageTools`) and return its result: the text of an MCP-style `content` array, or JSON for any other value. A tool that throws or rejects reports its error. The tool runs the site's own code and may change the page or act on the user's account, so treat a tool without `readOnlyHint` like a form submit. + + Args: + name: Tool name, as `pageTools` lists it. + arguments: Optional. The tool's input, matching its `inputSchema`. Defaults to {}. + """ + return await self.call("callPageTool", name=name, arguments=arguments) async def classify(self, *, questions: str | dict | list, selector: str | None = None, presets: bool | None = None) -> Any: """Classify the page or an element subtree using TypeSafe System One (Jev). `questions` is a JSON array of categories (returns the one that fits), or a JSON object of questions keyed by the name each answer comes back under: `true` for a preset (isBlocked, isCaptcha, isConsentWall, isEmptyCatalog, isErrorPage, isLoginWall, isPaywall, isUnsupportedBrowser, isLoading; an empty object `{}` asks all of them), a string for a yes/no question (returns its probability), `{question, options}` for a choice, or `{question, levels}` for a score on 2-10 levels ordered low to high (returns the `score` between level indices, the nearest `level`, and per-level `probabilities`). A missing answer is null. @@ -516,6 +583,14 @@ async def detect_forms(self, *, url: str | None = None, timeout: int | None = No timeout: Optional timeout in milliseconds. Defaults to 10000. """ return await self.call("detectForms", url=url, timeout=timeout) + async def download(self, *, url: str, path: str) -> Any: + """Fetch a URL and save the response body to a local file, sending the session's cookies so authenticated sites work. The way to get a binary or large document (PDF, spreadsheet, archive) out of the browser. Nothing is saved unless the status is 200-203 (like Chrome), and a failed download leaves an existing file at `path` untouched. Requires a loaded page — it fails before the first `goto`. + + Args: + url: Absolute http(s) URL to fetch. + path: Relative path (no '..' segments) to save the response body to. Created or overwritten. The response reports the absolute location. + """ + return await self.call("download", url=url, path=path) async def evaluate(self, *, script: str, url: str | None = None, timeout: int | None = None, save: str | None = None) -> Any: """Evaluate JavaScript in the current page context — an escape hatch for page-side logic the dedicated tools can't express; prefer `extract` for data and click/fill/etc. for actions. It runs in the page, so it cannot see the agent script's variables or builtins — interpolate any value into the `script` string. A bare trailing expression yields its value; top-level `await` and `return` are supported (the body then runs as an async function, so use `return` to produce a value). Objects and arrays return as JSON, so no `JSON.stringify` is needed. If a url is provided, it navigates there first. The `globalThis.lp` object exposes a Session-scoped bridge store: values written via `lp.foo = ...` auto-sync at end of evaluate, surviving navigation; values previously set via `/extract save=` or `/evaluate save=` appear as `lp.`. @@ -655,7 +730,20 @@ async def links(self, *, limit: int | None = None, url: str | None = None, timeo timeout: Optional timeout in milliseconds. Defaults to 10000. """ return await self.call("links", limit=limit, url=url, timeout=timeout) - async def markdown(self, *, selector: str | None = None, backend_node_id: int | None = None, max_bytes: int | None = None, strip: dict | None = None, url: str | None = None, timeout: int | None = None) -> Any: + async def login(self, *, password: str, username: str | None = None, username_selector: str | None = None, password_selector: str | None = None, submit_selector: str | None = None, next_selector: str | None = None, decide_only: bool | None = None) -> Any: + """Sign in on the current page. The browser collects the candidate fields and sign-in controls, asks TypeSafe System One (Jev) only what the markup leaves ambiguous, fills the credentials, submits, and re-reads the page to say whether it worked. A password is only ever typed into an `input[type=password]`, and credentials only go to an https (or loopback) page whose form posts to an https URL. Pass `$LP_*` placeholders rather than literal secrets: they resolve inside the browser and never appear in the result. Returns JSON with the selectors it used, so a recorded call replays them with no model call. Otherwise needs TYPESAFE_API_KEY. + + Args: + password: The password, as a $LP_* placeholder. + username: The username, email or other identifier, as a $LP_* placeholder. Omit on a page that asks only for the password. + username_selector: Optional CSS selector of the identifier field, from an earlier call's result. Given with passwordSelector, the fields are filled with no model call. + password_selector: Optional CSS selector of the password field, from an earlier call's result. Must name an input[type=password]. + submit_selector: Optional CSS selector of the control that submits the form. Without it, Enter is pressed in the filled field. + next_selector: Optional CSS selector of the control that submits the username on a page that asks for the password on a later step. Without it, Enter is pressed in the username field. + decide_only: Report which fields would be used and type nothing. For checking the picks on a page without sending credentials. + """ + return await self.call("login", password=password, username=username, username_selector=username_selector, password_selector=password_selector, submit_selector=submit_selector, next_selector=next_selector, decide_only=decide_only) + async def markdown(self, *, selector: str | None = None, backend_node_id: int | None = None, max_bytes: int | None = None, strip: dict | None = None, url: str | None = None, alternate: bool | None = None, timeout: int | None = None) -> Any: """Render the page (or a subtree) as markdown. Scope with `selector` or `backendNodeId` to read just the relevant region — full-page markdown is the last resort. Use `maxBytes` to cap long pages. Args: @@ -664,9 +752,10 @@ async def markdown(self, *, selector: str | None = None, backend_node_id: int | max_bytes: Optional soft cap on output size in bytes. Content is truncated at a UTF-8 boundary and a short '[truncated]' marker is appended past the cap. strip: Optional. Omit element groups from the output; same groups as the html tool's strip. `shell` (page chrome by markup) and `clutter` (keep only the main content, in the manner of reader modes) are the ones that matter for reading; `ui` also drops images. url: Optional URL to navigate to before rendering. An empty string is treated as omitted. + alternate: Optional. When the page links a markdown version of itself (), return that file instead of converting the page. It is the author's file and can differ from the rendered page; the output then starts with a comment naming its URL, which maxBytes does not count. Falls back to the page when there is no such link, the page itself failed to load (HTTP error status or bot challenge), or the alternate does not load as markdown within what is left of the timeout. Cannot be combined with selector or backendNodeId. Defaults to false. timeout: Optional timeout in milliseconds. Defaults to 10000. """ - return await self.call("markdown", selector=selector, backend_node_id=backend_node_id, max_bytes=max_bytes, strip=strip, url=url, timeout=timeout) + return await self.call("markdown", selector=selector, backend_node_id=backend_node_id, max_bytes=max_bytes, strip=strip, url=url, alternate=alternate, timeout=timeout) async def node_details(self, *, backend_node_id: int) -> Any: """Details for a node by backendNodeId: a ready-to-use CSS `selector` that resolves to the node (the first match, as click/fill resolve it), plus tag, role, name, interactivity, disabled, value, input type, placeholder, href, id, class, checked, select options. The canonical way to turn a tree backendNodeId into a CSS selector. @@ -674,6 +763,9 @@ async def node_details(self, *, backend_node_id: int) -> Any: backend_node_id: The backend node ID of the element to inspect. """ return await self.call("nodeDetails", backend_node_id=backend_node_id) + async def page_tools(self) -> Any: + """List the tools the current page registers for agents through WebMCP (`navigator.modelContext.registerTool`), as JSON with each tool's `name`, `description`, `inputSchema` and hints. A page tool runs the site's own code and can be more reliable than driving its UI; call one with `callPageTool`. Many pages register their tools after `load`: if the list is empty on a page you expect to have tools, call `waitForState` with `networkidle` and list again.""" + return await self.call("pageTools") async def press(self, *, key: str, selector: str | None = None, backend_node_id: int | None = None) -> PageResult: """Press a keyboard key, dispatching keydown and keyup events. Use key names like 'Enter', 'Tab', 'Escape', 'ArrowDown', 'Backspace', or single characters like 'a', '1'. Common shorthand is normalized: 'enter'/'return' → 'Enter', 'esc' → 'Escape', 'up'/'down'/'left'/'right' → 'Arrow*', 'space' → ' '. Pressing 'Enter' on a form input or submit button triggers implicit form submission. @@ -690,6 +782,15 @@ async def press(self, *, key: str, selector: str | None = None, backend_node_id: - `title`: Document title. Empty or absent when the page has none. """ return await self.call("press", key=key, selector=selector, backend_node_id=backend_node_id) + async def run(self, *, script: str | None = None, path: str | None = None, timeout: int | None = None) -> Any: + """Run a Lightpanda agent script in this session, as `lightpanda run` does, and return its console output followed by the value it returns. Pass the source as `script`, or the `path` of a file `save` wrote. The script drives pages through `const page = new Page(); await page.goto(url);` and the builtins as methods on `page`; `$LP_*` placeholders are resolved. Pages the script opens are closed when it ends; cookies and storage stay in the session, so a login carries over to the next call. Script variables do not carry over. A thrown error, a failed step or the timeout ends the script and is reported as an error after the output so far. + + Args: + script: The agent script source, as `save` writes it or `lightpanda run` takes it. Pass this or `path`. + path: A script file to run instead of `script`, such as one `save` wrote. Relative to the server's working directory. + timeout: Optional. Milliseconds before the script is stopped and reported as an error with its output so far. At least 1; defaults to 60000. + """ + return await self.call("run", script=script, path=path, timeout=timeout) async def screenshot(self, *, path: str | None = None, selector: str | None = None, backend_node_id: int | None = None, full_page: bool | None = None, strip: dict | None = None, url: str | None = None, timeout: int | None = None) -> Any: """Render the page, or one node, as a PNG: the text layout Lightpanda computes, not a pixel-accurate browser rendering (no images, fonts or CSS colours). With `path`, writes the file at full size and returns its location; without it, returns the image inline where the client can display one, at most 1280px wide and 4096px tall. Use it to see spatial layout; read content with `markdown`/`tree`. @@ -721,7 +822,7 @@ async def scroll(self, *, selector: str | None = None, backend_node_id: int | No """ return await self.call("scroll", selector=selector, backend_node_id=backend_node_id, x=x, y=y) async def search(self, *, query: str, timeout: int | None = None) -> Any: - """Run a web search and return results as markdown: a numbered list of {title, url, snippet}. Search tries brave, tavily, exa, then keenable in order, each when its API key (BRAVE_API_KEY, TAVILY_API_KEY, EXA_API_KEY or KEENABLE_API_KEY) is set; keenable also works without a key through its public endpoint (rate-limited per client IP). Prefer this over goto-ing google.com/search directly (Google blocks the browser on User-Agent/TLS). The browser does not navigate — to open a result, use `goto` with its URL. + """Run a web search and return results as markdown: a numbered list of {title, url, snippet}. Search tries brave, tavily, exa, parallel, then keenable in order, each when its API key (BRAVE_API_KEY, TAVILY_API_KEY, EXA_API_KEY, PARALLEL_API_KEY or KEENABLE_API_KEY) is set; keenable also works without a key through its public endpoint (rate-limited per client IP). Prefer this over goto-ing google.com/search directly (Google blocks the browser on User-Agent/TLS). The browser does not navigate — to open a result, use `goto` with its URL. Args: query: The search query. @@ -852,14 +953,15 @@ async def html(self, *, max_bytes: int | None = None, strip: dict | None = None) strip: Optional. Omit element groups from the output: `js` (script, noscript, script preloads), `css` (style, stylesheet links), `ui` (css plus img, picture, video, audio, svg, canvas, iframe), `invisible` (elements an author rule or inline style sets to display:none), `shell` (nav, aside, dialog, page-level header/footer and the matching landmark roles; skipped when that would drop most of the text), `clutter` (keep only the main content, in the manner of reader modes; includes `shell` and `invisible`, and falls back to `shell` when it finds too little). {"js":true,"css":true} keeps a page dump small. """ return await self.call("html", max_bytes=max_bytes, strip=strip) - async def markdown(self, *, max_bytes: int | None = None, strip: dict | None = None) -> Any: + async def markdown(self, *, max_bytes: int | None = None, strip: dict | None = None, alternate: bool | None = None) -> Any: """Render the page (or a subtree) as markdown. Scope with `selector` or `backendNodeId` to read just the relevant region — full-page markdown is the last resort. Use `maxBytes` to cap long pages. Args: max_bytes: Optional soft cap on output size in bytes. Content is truncated at a UTF-8 boundary and a short '[truncated]' marker is appended past the cap. strip: Optional. Omit element groups from the output; same groups as the html tool's strip. `shell` (page chrome by markup) and `clutter` (keep only the main content, in the manner of reader modes) are the ones that matter for reading; `ui` also drops images. + alternate: Optional. When the page links a markdown version of itself (), return that file instead of converting the page. It is the author's file and can differ from the rendered page; the output then starts with a comment naming its URL, which maxBytes does not count. Falls back to the page when there is no such link, the page itself failed to load (HTTP error status or bot challenge), or the alternate does not load as markdown within what is left of the timeout. Cannot be combined with selector or backendNodeId. Defaults to false. """ - return await self.call("markdown", max_bytes=max_bytes, strip=strip) + return await self.call("markdown", max_bytes=max_bytes, strip=strip, alternate=alternate) async def node_details(self) -> Any: """Details for a node by backendNodeId: a ready-to-use CSS `selector` that resolves to the node (the first match, as click/fill resolve it), plus tag, role, name, interactivity, disabled, value, input type, placeholder, href, id, class, checked, select options. The canonical way to turn a tree backendNodeId into a CSS selector.""" return await self.call("nodeDetails") From 0984432449612a3e303287640a8decf66d2e71d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Mon, 2 Nov 2026 18:26:23 +0100 Subject: [PATCH 20/21] Time each triage decision apart from the page load --- examples/README.md | 102 +++++++++++++++++++++------------------ examples/triage_crawl.py | 34 ++++++++----- 2 files changed, 78 insertions(+), 58 deletions(-) diff --git a/examples/README.md b/examples/README.md index 1329bb9..b91aa67 100644 --- a/examples/README.md +++ b/examples/README.md @@ -251,12 +251,17 @@ A score falls between its levels (0 = none, 2 = plenty). Scores vary a little between runs. The `jev` time is the whole call: the browser reading the page, then the round trip to TypeSafe, which reuses one connection after the first. -Needs `TYPESAFE_API_KEY`, and a browser with the `classify` tool. Until a -release ships both, the script installs this checkout rather than the PyPI -package, so run it from here against a local browser build: +Needs `TYPESAFE_API_KEY` and a `lightpanda` release with `judge()`: ```bash -LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/classify_pages.py +uv run examples/classify_pages.py +``` + +To run it from this checkout against a local browser build instead, use the +project's environment: + +```bash +LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run python examples/classify_pages.py ``` ## `triage_crawl.py` — crawl real sites in parallel and act on what Jev sees @@ -275,7 +280,9 @@ QUESTIONS = { } verdict = await page.judge(questions=QUESTIONS) -if verdict.answers["rate_limited"] >= 0.5: +if verdict.http_status is not None: # 4xx or 5xx: judged by status, no answers + ... +elif verdict.answers["rate_limited"] >= 0.5: await asyncio.sleep(3) # and load it again elif verdict.is_consent_wall: found = await page.find_element(role="button", name="/^(accept|aceptar|akzeptieren)/i") @@ -284,47 +291,49 @@ elif verdict.is_consent_wall: Every verdict prints a line. One the crawler acts on says `retry` and what it does about it, and the page's last verdict says `keep` or `skip`, so the two -cookie walls show up twice and a rate-limited page once per try: +cookie walls show up twice and a rate-limited page once per try. `decision` is +the `judge()` call alone, `total` the page so far, load and any retries +included. A page that answered 4xx or 5xx is judged by its status without +asking Jev, so it shows the status instead of a decision time: ``` -keep docs.python.org/3/library/asyncio.html docs 0.47s -keep developer.mozilla.org/en-US/docs/Web/API/Fet docs 0.69s -keep en.wikipedia.org/wiki/Headless_browser article 0.71s -keep en.wikipedia.org/wiki/Web_scraping article 0.93s -keep quotes.toscrape.com/js/ listing 1.00s -keep books.toscrape.com/catalogue/a-light-in-the- product 1.24s -keep lobste.rs/ listing 1.12s -keep www.spiegel.de/ listing 1.21s -keep github.com/lightpanda-io/browser listing 1.60s -keep news.ycombinator.com/ listing 1.15s -keep news.ycombinator.com/newest listing 1.31s -skip www.g2.com/ blocked 0.35s -retry news.ycombinator.com/login rate limited 0.98s -> back off 3s -skip github.com/settings/profile login wall 1.01s -retry www.20minutes.fr/ consent wall 1.33s -> accept cookies -skip www.wsj.com/ captcha 0.59s -skip www.economist.com/leaders/2024/01/04/what-to blocked 0.39s -skip www.linkedin.com/feed/ login wall 1.61s -skip stackoverflow.com/questions/231767/what-does blocked 0.49s -skip pypi.org/project/lightpanda/ captcha 0.74s -skip www.zeit.de/index error page 0.35s -retry www.elmundo.es/ consent wall 3.01s -> accept cookies -skip www.npmjs.com/search?q=xqzzzvqkplorbt empty catalog 1.02s -skip web.whatsapp.com/ unsupported browser 1.07s -skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog 1.59s -skip www.python.org/no-such-page error page 0.94s -skip news.ycombinator.com/login login wall 4.36s -skip arxiv.org/abs/1706.03762 error page 0.40s -keep www.elmundo.es/ other 5.23s -skip github.com/lightpanda-io/does-not-exist error page 0.92s -skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog 1.55s -skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt error page 0.60s -keep www.20minutes.fr/ other 6.11s - -30 pages in 10.1s with 6 crawlers (41.0s of page time): 13 kept, 17 skipped -Jev: 33 calls, median 0.22s, p90 0.30s -skipped: error page 5, login wall 3, blocked 3, empty catalog 3, captcha 2, unsupported browser 1 -acted: accept cookies 2, back off 1 +keep docs.python.org/3/library/asyncio.html docs decision 0.23s total 0.40s +keep en.wikipedia.org/wiki/Headless_browser article decision 0.23s total 0.52s +keep en.wikipedia.org/wiki/Web_scraping article decision 0.23s total 0.53s +keep quotes.toscrape.com/js/ listing decision 0.14s total 0.90s +keep books.toscrape.com/catalogue/a-light-in-the- product decision 0.14s total 1.17s +keep www.spiegel.de/ listing decision 0.31s total 0.85s +keep github.com/lightpanda-io/browser docs decision 0.21s total 1.07s +keep lobste.rs/ listing decision 0.15s total 1.08s +keep news.ycombinator.com/ listing decision 0.22s total 1.15s +keep news.ycombinator.com/newest listing decision 0.15s total 1.06s +retry www.20minutes.fr/ consent wall decision 0.15s total 0.94s -> accept cookies +skip news.ycombinator.com/login login wall decision 0.14s total 0.88s +skip www.g2.com/ blocked http 403 total 0.19s +skip github.com/settings/profile login wall decision 0.17s total 0.91s +skip www.economist.com/leaders/2024/01/04/what-to blocked http 403 total 0.23s +skip www.wsj.com/ login wall http 401 total 0.59s +skip stackoverflow.com/questions/231767/what-does blocked http 403 total 0.23s +skip www.zeit.de/index blocked http 403 total 0.09s +skip www.linkedin.com/feed/ login wall decision 0.15s total 1.47s +retry www.elmundo.es/ consent wall decision 0.18s total 2.60s -> accept cookies +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs decision 3.66s total 4.03s +skip www.npmjs.com/search?q=xqzzzvqkplorbt blocked http 403 total 0.42s +keep pypi.org/project/lightpanda/ product decision 0.15s total 1.29s +skip web.whatsapp.com/ unsupported browser decision 0.16s total 1.05s +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog decision 0.19s total 1.20s +skip arxiv.org/abs/1706.03762 blocked http 403 total 0.06s +skip www.python.org/no-such-page error page http 404 total 1.04s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt blocked http 403 total 0.38s +skip github.com/lightpanda-io/does-not-exist error page http 404 total 1.03s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog decision 0.17s total 2.75s +keep www.20minutes.fr/ listing decision 0.17s total 6.16s +keep www.elmundo.es/ other decision 0.17s total 8.07s + +30 pages in 9.7s with 6 crawlers (41.1s of page time): 14 kept, 16 skipped +Jev: 22 calls, median 0.17s, p90 0.29s +skipped: blocked 7, login wall 4, empty catalog 2, error page 2, unsupported browser 1 +acted: accept cookies 2 ``` What the walls actually showed: El Mundo's and 20 Minutes' cookie walls are @@ -340,8 +349,9 @@ how often Hacker News pushes back, or whether a challenge page scores as loads their pages in parallel. Known misses: Zillow's home page scores as an empty search, and Le Monde's front page leans paywall (0.71). -Runs from this checkout against a local browser build, like `classify_pages.py`: +Runs like `classify_pages.py`, from a release or from this checkout: ```bash -LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run examples/triage_crawl.py +uv run examples/triage_crawl.py +LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run python examples/triage_crawl.py ``` diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py index 9b37db5..f668ccb 100644 --- a/examples/triage_crawl.py +++ b/examples/triage_crawl.py @@ -81,13 +81,19 @@ def paint(text, color): async def judge(page): + """The verdict and the seconds Jev took to reach it.""" start = perf_counter() verdict = await page.judge(questions=QUESTIONS) - jev_times.append(perf_counter() - start) - return verdict + decision = perf_counter() - start + if verdict.http_status is None: # a 4xx or 5xx page is judged without Jev + jev_times.append(decision) + return verdict, decision def rate_limited(verdict): + # A 4xx or 5xx page is judged by its status alone, so our question has no answer. + if verdict.http_status is not None: + return verdict.http_status == 429 return verdict.answers["rate_limited"] >= 0.5 @@ -107,7 +113,7 @@ async def visit(page, url): start = perf_counter() actions = [] - def show(verdict, action=None, detail=""): + def show(verdict, decision, action=None, detail=""): if action: actions.append(action) status, note = paint("retry", "yellow"), paint(f" -> {action}{detail}", "yellow") @@ -115,34 +121,38 @@ def show(verdict, action=None, detail=""): status, note = paint("keep ", "green"), "" else: status, note = paint("skip ", "red"), "" - took = paint(f"{perf_counter() - start:.2f}s", "dim") + if verdict.http_status is None: + decided = f"decision {decision:.2f}s" + else: + decided = f"http {verdict.http_status:<9}" + took = paint(f"{decided} total {perf_counter() - start:5.2f}s", "dim") print(f"{status} {name:<44} {describe(verdict):<22} {took}{note}") await page.goto(url=url) - verdict = await judge(page) + verdict, decision = await judge(page) for attempt in (1, 2): if not rate_limited(verdict): break - show(verdict, "back off", f" {3 * attempt}s") + show(verdict, decision, "back off", f" {3 * attempt}s") await asyncio.sleep(3 * attempt) await page.goto(url=url) - verdict = await judge(page) + verdict, decision = await judge(page) if verdict.is_consent_wall: found = await page.find_element(role="button", name=ACCEPT) if found: - show(verdict, "accept cookies") + show(verdict, decision, "accept cookies") await found[0].click() await page.wait_for_state(state="networkidle") # banners fade out - verdict = await judge(page) + verdict, decision = await judge(page) if verdict.is_loading: - show(verdict, "wait") + show(verdict, decision, "wait") await page.wait_for_state(state="networkidle") - verdict = await judge(page) + verdict, decision = await judge(page) - show(verdict) + show(verdict, decision) return verdict, actions From cb93ad4830a7e65d0568e2f96a7ce607aa716218 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Arrufat?= Date: Mon, 2 Nov 2026 18:27:35 +0100 Subject: [PATCH 21/21] Refresh the triage crawl sample --- examples/README.md | 68 +++++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/examples/README.md b/examples/README.md index b91aa67..f4d1171 100644 --- a/examples/README.md +++ b/examples/README.md @@ -297,41 +297,41 @@ included. A page that answered 4xx or 5xx is judged by its status without asking Jev, so it shows the status instead of a decision time: ``` -keep docs.python.org/3/library/asyncio.html docs decision 0.23s total 0.40s -keep en.wikipedia.org/wiki/Headless_browser article decision 0.23s total 0.52s -keep en.wikipedia.org/wiki/Web_scraping article decision 0.23s total 0.53s -keep quotes.toscrape.com/js/ listing decision 0.14s total 0.90s -keep books.toscrape.com/catalogue/a-light-in-the- product decision 0.14s total 1.17s -keep www.spiegel.de/ listing decision 0.31s total 0.85s -keep github.com/lightpanda-io/browser docs decision 0.21s total 1.07s -keep lobste.rs/ listing decision 0.15s total 1.08s -keep news.ycombinator.com/ listing decision 0.22s total 1.15s -keep news.ycombinator.com/newest listing decision 0.15s total 1.06s -retry www.20minutes.fr/ consent wall decision 0.15s total 0.94s -> accept cookies -skip news.ycombinator.com/login login wall decision 0.14s total 0.88s -skip www.g2.com/ blocked http 403 total 0.19s -skip github.com/settings/profile login wall decision 0.17s total 0.91s -skip www.economist.com/leaders/2024/01/04/what-to blocked http 403 total 0.23s -skip www.wsj.com/ login wall http 401 total 0.59s +keep en.wikipedia.org/wiki/Headless_browser article decision 0.25s total 0.53s +keep en.wikipedia.org/wiki/Web_scraping article decision 0.29s total 0.58s +keep developer.mozilla.org/en-US/docs/Web/API/Fet docs decision 0.24s total 0.59s +keep docs.python.org/3/library/asyncio.html docs decision 0.27s total 0.66s +keep quotes.toscrape.com/js/ listing decision 0.15s total 0.91s +keep books.toscrape.com/catalogue/a-light-in-the- product decision 0.16s total 1.18s +keep lobste.rs/ listing decision 0.14s total 0.91s +keep www.spiegel.de/ listing decision 0.30s total 1.01s +keep news.ycombinator.com/ listing decision 0.16s total 1.09s +keep news.ycombinator.com/newest listing decision 0.14s total 1.07s +keep github.com/lightpanda-io/browser docs decision 0.22s total 1.64s +skip news.ycombinator.com/login login wall decision 0.14s total 0.68s +skip www.g2.com/ blocked http 403 total 0.35s +skip www.wsj.com/ login wall http 401 total 0.46s +skip www.economist.com/leaders/2024/01/04/what-to blocked http 403 total 0.25s +retry www.20minutes.fr/ consent wall decision 0.19s total 1.39s -> accept cookies skip stackoverflow.com/questions/231767/what-does blocked http 403 total 0.23s -skip www.zeit.de/index blocked http 403 total 0.09s -skip www.linkedin.com/feed/ login wall decision 0.15s total 1.47s -retry www.elmundo.es/ consent wall decision 0.18s total 2.60s -> accept cookies -keep developer.mozilla.org/en-US/docs/Web/API/Fet docs decision 3.66s total 4.03s -skip www.npmjs.com/search?q=xqzzzvqkplorbt blocked http 403 total 0.42s -keep pypi.org/project/lightpanda/ product decision 0.15s total 1.29s -skip web.whatsapp.com/ unsupported browser decision 0.16s total 1.05s -skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog decision 0.19s total 1.20s -skip arxiv.org/abs/1706.03762 blocked http 403 total 0.06s -skip www.python.org/no-such-page error page http 404 total 1.04s -skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt blocked http 403 total 0.38s -skip github.com/lightpanda-io/does-not-exist error page http 404 total 1.03s -skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog decision 0.17s total 2.75s -keep www.20minutes.fr/ listing decision 0.17s total 6.16s -keep www.elmundo.es/ other decision 0.17s total 8.07s - -30 pages in 9.7s with 6 crawlers (41.1s of page time): 14 kept, 16 skipped -Jev: 22 calls, median 0.17s, p90 0.29s +skip www.zeit.de/index blocked http 403 total 0.07s +skip github.com/settings/profile login wall decision 0.18s total 1.39s +skip www.linkedin.com/feed/ login wall decision 0.17s total 1.26s +skip www.npmjs.com/search?q=xqzzzvqkplorbt blocked http 403 total 0.39s +keep pypi.org/project/lightpanda/ product decision 0.22s total 1.06s +retry www.elmundo.es/ consent wall decision 0.18s total 2.76s -> accept cookies +skip web.whatsapp.com/ unsupported browser decision 0.15s total 1.05s +skip www.python.org/no-such-page error page http 404 total 0.46s +skip arxiv.org/abs/1706.03762 blocked http 403 total 0.07s +skip en.wikipedia.org/w/index.php?search=xqzzzvqk empty catalog decision 0.17s total 1.22s +skip github.com/search?q=xqzzzvqkplorbt&type=repo empty catalog decision 0.35s total 1.73s +skip www.ebay.com/sch/i.html?_nkw=xqzzzvqkplorbt blocked http 403 total 0.77s +skip github.com/lightpanda-io/does-not-exist error page http 404 total 1.23s +keep www.elmundo.es/ other decision 0.16s total 5.04s +keep www.20minutes.fr/ listing decision 0.15s total 6.62s + +30 pages in 8.2s with 6 crawlers (34.7s of page time): 14 kept, 16 skipped +Jev: 22 calls, median 0.18s, p90 0.30s skipped: blocked 7, login wall 4, empty catalog 2, error page 2, unsupported browser 1 acted: accept cookies 2 ```