diff --git a/examples/README.md b/examples/README.md index 9b37986..f4d1171 100644 --- a/examples/README.md +++ b/examples/README.md @@ -7,6 +7,8 @@ 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 +uv run examples/triage_crawl.py # needs TYPESAFE_API_KEY ``` Set `LIGHTPANDA_BIN=/path/to/lightpanda` to run against a local browser build @@ -214,3 +216,142 @@ 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 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. 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(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 +else: + print(verdict.answers["kind"]["choice"]) # product +``` + +``` +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 +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 `lightpanda` release with `judge()`: + +```bash +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 + +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 +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.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") + 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 the two +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 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.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 +``` + +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 +`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 like `classify_pages.py`, from a release or from this checkout: + +```bash +uv run examples/triage_crawl.py +LIGHTPANDA_BIN=../browser/zig-out/bin/lightpanda uv run python examples/triage_crawl.py +``` diff --git a/examples/classify_pages.py b/examples/classify_pages.py new file mode 100644 index 0000000..f7c7272 --- /dev/null +++ b/examples/classify_pages.py @@ -0,0 +1,65 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["lightpanda"] +# /// +"""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 = [ + "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", + "https://www.g2.com/", +] + +QUESTIONS = { + # yes/no + "has_price": "Does the page show a price?", + # choice + "kind": { + "question": "What kind of page is this?", + "options": ["product", "listing", "article", "other"], + }, + # score + "content": { + "question": "How much useful content would a scraper get from this page?", + "levels": ["none", "little", "plenty"], + }, +} + + +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: + _, 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:<38} {times}") + continue + + 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}) {times}" + ) diff --git a/examples/triage_crawl.py b/examples/triage_crawl.py new file mode 100644 index 0000000..f668ccb --- /dev/null +++ b/examples/triage_crawl.py @@ -0,0 +1,201 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["lightpanda"] +# /// +"""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: 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 +""" + +import asyncio +import statistics +import sys +from collections import Counter +from time import perf_counter + +from lightpanda import AsyncBrowser, LightpandaError + +# Pages loading at once, each in its own session of one browser. +CRAWLERS = 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.elmundo.es/", + "https://www.20minutes.fr/", + # 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() +jev_times = [] + + +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 + + +async def judge(page): + """The verdict and the seconds Jev took to reach it.""" + start = perf_counter() + verdict = await page.judge(questions=QUESTIONS) + 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 + + +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` 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, decision, 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"), "" + 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, decision = await judge(page) + + for attempt in (1, 2): + if not rate_limited(verdict): + break + show(verdict, decision, "back off", f" {3 * attempt}s") + await asyncio.sleep(3 * attempt) + await page.goto(url=url) + verdict, decision = await judge(page) + + if verdict.is_consent_wall: + found = await page.find_element(role="button", name=ACCEPT) + if found: + show(verdict, decision, "accept cookies") + await found[0].click() + await page.wait_for_state(state="networkidle") # banners fade out + verdict, decision = await judge(page) + + if verdict.is_loading: + show(verdict, decision, "wait") + await page.wait_for_state(state="networkidle") + verdict, decision = await judge(page) + + show(verdict, decision) + return verdict, actions + + +async def triage(browser, slots, url): + """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')} {url.split('://', 1)[1][:44]:<44} {err}") + return "failed", [], perf_counter() - start + took = perf_counter() - start + outcome = "kept" if verdict.ok and not rate_limited(verdict) else describe(verdict) + return outcome, actions, took + + +async def main(): + slots = asyncio.Semaphore(CRAWLERS) + start = perf_counter() + async with AsyncBrowser() as browser: + results = await asyncio.gather(*(triage(browser, slots, url) for url in URLS)) + elapsed = perf_counter() - start + + 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) + + 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" + ) + 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())) + + +asyncio.run(main()) 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 85229d3..c4cb1bd 100644 --- a/lightpanda/_methods.py +++ b/lightpanda/_methods.py @@ -20,6 +20,31 @@ 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. + + 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, 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. @@ -46,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.`. @@ -185,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: @@ -194,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. @@ -204,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. @@ -220,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`. @@ -251,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. @@ -382,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") @@ -472,6 +532,31 @@ 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. + + 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, 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. @@ -498,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.`. @@ -637,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: @@ -646,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. @@ -656,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. @@ -672,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`. @@ -703,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. @@ -834,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") diff --git a/lightpanda/async_browser.py b/lightpanda/async_browser.py index b1eb5cd..6b743f1 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, *, 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, questions=questions, 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..61ae108 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 @@ -58,6 +58,107 @@ 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 + ``` + + 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 + """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 + """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 + """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.""" + 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.""" + 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) + 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) + 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: + """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})" + + +# 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"(? 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 + ``` + + 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) + 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.""" name = self._snake_map.get(attr) 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..37827a0 --- /dev/null +++ b/tests/test_classify.py @@ -0,0 +1,149 @@ +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, the top level for a score.""" + + 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} + 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) + 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" + + +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: + 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 + + +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 + + +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 + + async with AsyncBrowser.wrap(classify_browser).session() as page: + await page.goto(url=f"{fixture_url}/index.html") + assert (await page.judge()).is_captcha