Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(captcha): element-tree placeholder for visible Cloudflare Turnstile frames (SKY-11616) (#7102)
LawyZheng54bc8689313e
diff --git a/skyvern/webeye/scraper/scraped_page.py b/skyvern/webeye/scraper/scraped_page.pyindex ab3c6d0b5..123ff99cc 100644--- a/skyvern/webeye/scraper/scraped_page.py+++ b/skyvern/webeye/scraper/scraped_page.py@@ -3,6 +3,7 @@ import jsonimport reimport typingfrom abc import ABC, abstractmethod+from dataclasses import dataclassfrom enum import StrEnumfrom typing import Any, Awaitable, Callable, Self@@ -20,7 +21,24 @@ if typing.TYPE_CHECKING:LOG = structlog.get_logger()CleanupElementTreeFunc = Callable[[Page | Frame, str, list[dict]], Awaitable[list[dict]]]-ScrapeExcludeFunc = Callable[[Page, Frame], Awaitable[bool]]+++@dataclass+class ScrapeFrameDecision:+ """Result of a scrape-frame filter callback.++ ``exclude`` drops the frame from the scraped element tree. ``placeholder``, when+ set, is a non-interactable element-tree node appended in the frame's place — a+ signal node for a frame the tree would otherwise miss (e.g. a cross-origin captcha+ living inside a closed shadow root). Placeholders are tree-only: they are never+ added to the flat interactable elements list, so they can never become a target.+ """++ exclude: bool+ placeholder: dict | None = None+++ScrapeExcludeFunc = Callable[[Page, Frame], Awaitable[ScrapeFrameDecision]]ELEMENT_NODE_ATTRIBUTES = {"id",diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.pyindex 6b7080889..31a336eb2 100644--- a/skyvern/webeye/scraper/scraper.py+++ b/skyvern/webeye/scraper/scraper.py@@ -278,9 +278,9 @@ async def get_frame_text(iframe: Frame, scrape_exclude: ScrapeExcludeFunc | None"""Get all the visible text in the iframe.:param iframe: Frame instance to get the text from.- :param scrape_exclude: Optional ``filter_frames``-style predicate; True- means skip. The top-level caller must pass a starting frame the- predicate would not itself exclude.+ :param scrape_exclude: Optional ``filter_frames``-style predicate returning a+ ``ScrapeFrameDecision``; ``exclude`` means skip. The top-level caller must pass+ a starting frame the predicate would not itself exclude.:return: All the visible text from the iframe."""js_script = "() => document.body.innerText"@@ -301,7 +301,7 @@ async def get_frame_text(iframe: Frame, scrape_exclude: ScrapeExcludeFunc | Nonecontinue# Skip excluded frames before any CDP probe.- if scrape_exclude is not None and await scrape_exclude(child_frame.page, child_frame):+ if scrape_exclude is not None and (await scrape_exclude(child_frame.page, child_frame)).exclude:continuetry:@@ -574,17 +574,34 @@ async def get_all_children_frames(page: Page) -> list[Frame]:return frames-async def filter_frames(frames: list[Frame], scrape_exclude: ScrapeExcludeFunc | None = None) -> list[Frame]:- filtered_frames = []+async def filter_frames(+ frames: list[Frame], scrape_exclude: ScrapeExcludeFunc | None = None+) -> tuple[list[Frame], list[dict]]:+ """Split ``frames`` into the ones to scrape and any placeholder nodes to inject.++ Placeholder nodes come from ``scrape_exclude`` callbacks that skip a frame but want+ a non-interactable signal node left in its place (e.g. a cross-origin captcha the+ element tree cannot otherwise reach). Identical placeholders are de-duplicated so a+ vendor rendering the same widget across several frames only surfaces once.+ """+ filtered_frames: list[Frame] = []+ placeholder_nodes: list[dict] = []for frame in frames:if frame.is_detached():continue- if scrape_exclude is not None and await scrape_exclude(frame.page, frame):+ if scrape_exclude is None:+ filtered_frames.append(frame)+ continue++ decision = await scrape_exclude(frame.page, frame)+ if decision.placeholder is not None and decision.placeholder not in placeholder_nodes:+ placeholder_nodes.append(decision.placeholder)+ if decision.exclude:continuefiltered_frames.append(frame)- return filtered_frames+ return filtered_frames, placeholder_nodesasync def add_frame_interactable_elements(@@ -655,8 +672,8 @@ async def get_interactable_element_tree()context = skyvern_context.ensure_context()- frames = await get_all_children_frames(page)- frames = await filter_frames(frames, scrape_exclude)+ all_frames = await get_all_children_frames(page)+ frames, placeholder_nodes = await filter_frames(all_frames, scrape_exclude)# Iframe-heavy pages dominate the 1.8s p95 here; frame_count lets us# slice element_tree latency by page complexity.otel_trace.get_current_span().set_attribute("frame_count", len(frames))@@ -677,6 +694,11 @@ async def get_interactable_element_tree(must_included_tags,)+ # Placeholder nodes stand in for frames the filter skipped but wants the LLM to+ # still see (e.g. a cross-origin captcha inside a closed shadow root). They join the+ # element tree only — never ``elements`` — so they can never become a click target.+ element_tree.extend(placeholder_nodes)+return elements, element_treediff --git a/tests/unit/test_get_frame_text_scrape_exclude.py b/tests/unit/test_get_frame_text_scrape_exclude.pyindex a9f64268a..30e19e052 100644--- a/tests/unit/test_get_frame_text_scrape_exclude.py+++ b/tests/unit/test_get_frame_text_scrape_exclude.py@@ -4,6 +4,7 @@ from urllib.parse import urlparseimport pytestfrom skyvern.webeye.scraper import scraper+from skyvern.webeye.scraper.scraped_page import ScrapeFrameDecisiondef _make_frame(url: str, child_frames: list | None = None) -> MagicMock:@@ -64,9 +65,9 @@ async def test_get_frame_text_skips_excluded_child_and_its_subtree() -> None:child_real = _make_frame("https://example.com/embed")main = _make_frame("https://example.com/", child_frames=[child_ad, child_real])- async def _exclude(page, frame) -> bool:+ async def _exclude(page, frame) -> ScrapeFrameDecision:hostname = urlparse(frame.url or "").hostname or ""- return hostname == "ads.example.invalid"+ return ScrapeFrameDecision(exclude=hostname == "ads.example.invalid")visited: list[str] = []@@ -96,9 +97,9 @@ async def test_get_frame_text_keeps_child_when_exclude_returns_false() -> None:exclude_calls: list[tuple[object, object]] = []- async def _exclude(page, frame) -> bool:+ async def _exclude(page, frame) -> ScrapeFrameDecision:exclude_calls.append((page, frame))- return False+ return ScrapeFrameDecision(exclude=False)visited: list[str] = []@@ -127,7 +128,7 @@ async def test_get_frame_text_still_skips_detached_children_before_predicate() -detached_child.is_detached = MagicMock(return_value=True)main = _make_frame("https://example.com/", child_frames=[detached_child])- async def _exclude(page, frame) -> bool:+ async def _exclude(page, frame) -> ScrapeFrameDecision:raise AssertionError("predicate must not run for detached frames")with patch.object(scraper.SkyvernFrame, "evaluate", new=AsyncMock(return_value="root")):diff --git a/tests/unit/test_scrape_frame_decision.py b/tests/unit/test_scrape_frame_decision.pynew file mode 100644index 000000000..86194f106--- /dev/null+++ b/tests/unit/test_scrape_frame_decision.py@@ -0,0 +1,198 @@+"""Generic scrape-frame decision seam.++``scrape_exclude`` callbacks return a ``ScrapeFrameDecision`` that carries the+exclude flag and an optional non-interactable placeholder node. These tests pin the+OSS plumbing — frame filtering, placeholder collection / de-duplication, and that+placeholders reach the element tree but never the flat interactable elements list —+without any vendor-specific (captcha) logic, which now lives in the cloud filter.++The browser-backed plumbing test is skipped in CI when Playwright browsers are not+installed.+"""++from __future__ import annotations++import asyncio+from pathlib import Path+from typing import AsyncIterator, Awaitable, Callable, Iterator+from unittest.mock import AsyncMock, MagicMock++import pytest+import pytest_asyncio+from playwright.async_api import Page, async_playwright++from skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext+from skyvern.webeye.scraper.scraped_page import ScrapeFrameDecision+from skyvern.webeye.scraper.scraper import filter_frames, get_interactable_element_tree+++def _has_playwright_browser() -> bool:+ try:+ from playwright.sync_api import sync_playwright # noqa: PLC0415++ with sync_playwright() as p:+ return Path(p.chromium.executable_path).exists()+ except Exception:+ return False+++_skip_no_browser = pytest.mark.skipif(+ not _has_playwright_browser(),+ reason="Requires Playwright browsers installed (run: playwright install chromium)",+)++_PLACEHOLDER = {+ "tagName": "iframe",+ "interactable": False,+ "attributes": {"title": "placeholder"},+ "text": "placeholder signal",+ "children": [],+}+++def _make_frame(detached: bool = False) -> MagicMock:+ frame = MagicMock()+ frame.is_detached = MagicMock(return_value=detached)+ frame.page = MagicMock()+ return frame+++class TestFilterFrames:+ @pytest.mark.asyncio+ async def test_exclude_drops_frame_and_yields_no_placeholder(self) -> None:+ keep, drop = _make_frame(), _make_frame()++ async def _exclude(page: object, frame: object) -> ScrapeFrameDecision:+ return ScrapeFrameDecision(exclude=frame is drop)++ frames, placeholders = await filter_frames([keep, drop], _exclude)+ assert frames == [keep]+ assert placeholders == []++ @pytest.mark.asyncio+ async def test_decision_excludes_frame_and_collects_placeholder(self) -> None:+ drop = _make_frame()++ async def _exclude(page: object, frame: object) -> ScrapeFrameDecision:+ return ScrapeFrameDecision(exclude=True, placeholder=_PLACEHOLDER)++ frames, placeholders = await filter_frames([drop], _exclude)+ assert frames == []+ assert placeholders == [_PLACEHOLDER]++ @pytest.mark.asyncio+ async def test_placeholder_can_accompany_a_kept_frame(self) -> None:+ keep = _make_frame()++ async def _exclude(page: object, frame: object) -> ScrapeFrameDecision:+ return ScrapeFrameDecision(exclude=False, placeholder=_PLACEHOLDER)++ frames, placeholders = await filter_frames([keep], _exclude)+ assert frames == [keep]+ assert placeholders == [_PLACEHOLDER]++ @pytest.mark.asyncio+ async def test_identical_placeholders_dedupe(self) -> None:+ f1, f2 = _make_frame(), _make_frame()++ async def _exclude(page: object, frame: object) -> ScrapeFrameDecision:+ return ScrapeFrameDecision(exclude=True, placeholder=dict(_PLACEHOLDER))++ _, placeholders = await filter_frames([f1, f2], _exclude)+ assert placeholders == [_PLACEHOLDER]++ @pytest.mark.asyncio+ async def test_detached_frames_skip_predicate(self) -> None:+ detached = _make_frame(detached=True)++ async def _exclude(page: object, frame: object) -> ScrapeFrameDecision:+ raise AssertionError("predicate must not run for detached frames")++ frames, placeholders = await filter_frames([detached], _exclude)+ assert frames == []+ assert placeholders == []++ @pytest.mark.asyncio+ async def test_no_predicate_keeps_all_live_frames(self) -> None:+ keep, detached = _make_frame(), _make_frame(detached=True)+ frames, placeholders = await filter_frames([keep, detached], None)+ assert frames == [keep]+ assert placeholders == []++[email protected](autouse=True)+def _skyvern_ctx() -> Iterator[None]:+ skyvern_context.set(SkyvernContext())+ yield+ skyvern_context.reset()+++@pytest_asyncio.fixture+async def page_factory() -> AsyncIterator[Callable[[str], Awaitable[Page]]]:+ async with async_playwright() as p:+ browser = await p.chromium.launch(headless=True)+ context = await browser.new_context()++ async def _make_page(html: str) -> Page:+ page = await context.new_page()+ await page.set_content(html, wait_until="domcontentloaded")+ await asyncio.sleep(0.2)+ return page++ yield _make_page++ await context.close()+ await browser.close()+++def _flatten(tree: list[dict]) -> list[dict]:+ flat: list[dict] = []+ queue = list(tree)+ while queue:+ node = queue.pop(0)+ flat.append(node)+ queue.extend(node.get("children", []))+ return flat+++@_skip_no_browser+class TestPlaceholderPlumbing:+ @pytest.mark.asyncio+ async def test_decision_placeholder_reaches_tree_but_not_elements(+ self, page_factory: Callable[[str], Awaitable[Page]]+ ) -> None:+ page = await page_factory(+ "<html><body><input id='name' type='text' />"+ "<iframe src='https://embed.example.com/widget' style='width:200px;height:80px'></iframe>"+ "</body></html>"+ )++ # Generic seam: skip the embed frame while injecting a signal node in its place.+ async def _exclude(p: object, frame: object) -> ScrapeFrameDecision:+ if frame == page.main_frame:+ return ScrapeFrameDecision(exclude=False)+ return ScrapeFrameDecision(exclude=True, placeholder=dict(_PLACEHOLDER))++ elements, element_tree = await get_interactable_element_tree(page, scrape_exclude=_exclude)++ tree_texts = [str(node.get("text", "")) for node in _flatten(element_tree)]+ assert "placeholder signal" in tree_texts+ element_texts = [str(el.get("text", "")) for el in elements]+ assert "placeholder signal" not in element_texts++ # real form controls survive in both the flat elements list and the tree+ flat_ids = {node.get("id") for node in _flatten(element_tree)}+ interactable_ids = {el["id"] for el in elements if el.get("interactable")}+ assert interactable_ids & flat_ids, "real controls stay in elements and tree"++ @pytest.mark.asyncio+ async def test_exclude_without_placeholder_injects_nothing(+ self, page_factory: Callable[[str], Awaitable[Page]]+ ) -> None:+ page = await page_factory("<html><body><input id='name' type='text' /></body></html>")++ exclude = AsyncMock(return_value=ScrapeFrameDecision(exclude=False))+ _, element_tree = await get_interactable_element_tree(page, scrape_exclude=exclude)++ assert all("placeholder signal" not in str(node.get("text", "")) for node in _flatten(element_tree))