Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix: use CSS selectors instead of xpaths in element-level fallback episodes (#5394)
pedrohsdbe9ae5940d6cc
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.pyindex a44045394..4f830b89e 100644--- a/skyvern/core/script_generations/real_skyvern_page_ai.py+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py@@ -21,6 +21,7 @@ from skyvern.forge.sdk.schemas.totp_codes import OTPTypefrom skyvern.schemas.workflows import BlockStatusfrom skyvern.services import script_servicefrom skyvern.services.otp_service import poll_otp_value+from skyvern.utils.css_selector import compute_stable_selectorfrom skyvern.utils.prompt_engine import load_prompt_with_elementsfrom skyvern.webeye.actions import handler_utilsfrom skyvern.webeye.actions.actions import (@@ -712,14 +713,13 @@ class RealSkyvernPageAi(SkyvernPageAi):if hasattr(action, "element_id"):action_data["element_id"] = action.element_idif hasattr(action, "skyvern_element_data") and action.skyvern_element_data:- # This contains xpath, tag, text, attributes — the data the reviewer- # needs to derive a stable selectorel_data = action.skyvern_element_data- action_data["element_tag"] = el_data.get("tag", "")- action_data["element_text"] = el_data.get("text", "")[:200]+ el_attrs = el_data.get("attributes") or {}+ action_data["element_tag"] = el_data.get("tagName", "")+ action_data["element_text"] = (el_data.get("text") or "")[:200]action_data["all_attributes"] = {k: v- for k, v in el_data.items()+ for k, v in el_attrs.items()if kin ("id",@@ -735,9 +735,16 @@ class RealSkyvernPageAi(SkyvernPageAi):"title",)}- xpath = action.get_xpath() if hasattr(action, "get_xpath") else None- if xpath:- action_data["css_suggestion"] = f"xpath={xpath}"+ # el_data already has the shape compute_stable_selector expects+ # (tagName, attributes dict, text) — pass it directly.+ css_sel = compute_stable_selector(el_data)+ if css_sel:+ action_data["css_suggestion"] = css_sel+ else:+ # Fall back to xpath only if no CSS selector can be derived+ xpath = action.get_xpath() if hasattr(action, "get_xpath") else None+ if xpath:+ action_data["css_suggestion"] = f"xpath={xpath}"if hasattr(action, "reasoning"):action_data["reasoning"] = action.reasoningdiff --git a/skyvern/utils/css_selector.py b/skyvern/utils/css_selector.pyindex 44b4b1329..b6256c415 100644--- a/skyvern/utils/css_selector.py+++ b/skyvern/utils/css_selector.py@@ -83,10 +83,11 @@ def compute_stable_selector(element_data: dict | None) -> str | None:def _looks_dynamic(value: str) -> bool:- """Heuristic: IDs with long hex/numeric suffixes are likely auto-generated."""- # Matches patterns like "ember123", "react-456", "el_abc123def", "uid-xxxx"+ """Heuristic: IDs that are likely auto-generated and will change across runs."""+ # Long hex strings (ember123, react-456, el_abc123def)if re.search(r"[0-9a-f]{8,}", value, re.IGNORECASE):return True+ # Word-digit patterns (uid-1234, el_5678)if re.search(r"^\w+[-_]\d{4,}$", value):return Truereturn Falsediff --git a/tests/unit/test_css_selector.py b/tests/unit/test_css_selector.pynew file mode 100644index 000000000..83a51a0ec--- /dev/null+++ b/tests/unit/test_css_selector.py@@ -0,0 +1,113 @@+"""Tests for compute_stable_selector and _looks_dynamic."""++from skyvern.utils.css_selector import _looks_dynamic, compute_stable_selector+++class TestLooksDynamic:+ """Tests for the _looks_dynamic heuristic."""++ def test_long_hex_ids_are_dynamic(self):+ assert _looks_dynamic("ember12345678") is True+ assert _looks_dynamic("react-abcdef01") is True++ def test_word_digit_ids_are_dynamic(self):+ assert _looks_dynamic("uid-12345") is True+ assert _looks_dynamic("el_56789") is True++ def test_semantic_ids_are_not_dynamic(self):+ """Meaningful IDs should NOT be flagged as dynamic."""+ assert _looks_dynamic("username") is False+ assert _looks_dynamic("sign_in") is False+ assert _looks_dynamic("passwd") is False+ assert _looks_dynamic("inputUsername") is False+ assert _looks_dynamic("login-form") is False+ assert _looks_dynamic("signOnButton") is False++ def test_single_char_ids_not_dynamic(self):+ """Very short IDs shouldn't match the all-caps pattern."""+ assert _looks_dynamic("A") is False+ assert _looks_dynamic("AB") is False++ def test_title_case_ids_not_dynamic(self):+ """Title-case or mixed-case IDs are likely meaningful, not generated."""+ assert _looks_dynamic("Login") is False+ assert _looks_dynamic("Form") is False+ assert _looks_dynamic("Nav") is False+ assert _looks_dynamic("Input") is False+ assert _looks_dynamic("Button") is False+++class TestComputeStableSelector:+ """Tests for compute_stable_selector priority and output."""++ def test_prefers_text_over_dynamic_id(self):+ """When ID is dynamic and text is available, use :has-text()."""+ elem = {+ "tagName": "button",+ "text": "Apply Filters",+ "attributes": {"id": "ember12345678", "type": "submit"},+ }+ result = compute_stable_selector(elem)+ assert result == 'button:has-text("Apply Filters")'++ def test_static_id_preferred_over_text(self):+ """When ID looks stable, use it (it's higher priority)."""+ elem = {+ "tagName": "button",+ "text": "Submit",+ "attributes": {"id": "signOnButton"},+ }+ result = compute_stable_selector(elem)+ assert result == "#signOnButton"++ def test_aria_label_preferred_over_text(self):+ elem = {+ "tagName": "input",+ "text": "",+ "attributes": {"aria-label": "Email Address", "id": "uid-12345"},+ }+ result = compute_stable_selector(elem)+ assert result == 'input[aria-label="Email Address"]'++ def test_realistic_scraper_shape(self):+ """Scraper output shape (from domUtils.js buildElementObject) should work directly.++ el_data has top-level 'id' (Skyvern uniqueId), 'tagName', 'text',+ and nested 'attributes' with real HTML attrs. The scraper stores+ unique_id as a separate attribute, not as 'id'.+ """+ el_data = {+ "id": "AAGD", # Skyvern unique_id — NOT the HTML id+ "tagName": "button",+ "attributes": {"unique_id": "AAGD", "type": "submit"},+ "text": "Apply Filters",+ "xpath": "/html/body/div/button",+ }+ result = compute_stable_selector(el_data)+ assert result == 'button:has-text("Apply Filters")'++ def test_realistic_scraper_shape_with_aria_label(self):+ """Scraper shape with aria-label should produce aria-label selector."""+ el_data = {+ "id": "AABC",+ "tagName": "input",+ "attributes": {"unique_id": "AABC", "aria-label": "Email Address", "type": "email"},+ "text": "",+ }+ result = compute_stable_selector(el_data)+ assert result == 'input[aria-label="Email Address"]'++ def test_realistic_scraper_shape_with_stable_html_id(self):+ """When the HTML id is stable (same as Skyvern id only by coincidence), use it."""+ el_data = {+ "id": "AAGD",+ "tagName": "button",+ "attributes": {"id": "signOnButton", "type": "submit"},+ "text": "Sign On",+ }+ result = compute_stable_selector(el_data)+ assert result == "#signOnButton"++ def test_no_data_returns_none(self):+ assert compute_stable_selector(None) is None+ assert compute_stable_selector({}) is None