Skip to content

Automate browser based workflows with AI

fix: use dynamic selectors for navigation blocks inside for-loops (#5434)

pedrohsdb45f76502666b
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.py
index bfa00f7c1..ccf7b5cbe 100644
--- a/skyvern/core/script_generations/generate_script.py
+++ b/skyvern/core/script_generations/generate_script.py
@@ -1153,13 +1153,15 @@ def _build_block_fn(
else:
body_stmts.append(cst.parse_statement(f"await page.goto({repr(url_str)})"))
- # For file_download blocks inside for-loops, generate a dynamic click that uses
- # per-iteration context instead of hardcoded xpath/prompt from iteration 0.
+ # For blocks inside for-loops that click on loop items, generate a dynamic click
+ # that uses per-iteration context instead of hardcoded xpath/prompt from iteration 0.
+ # loop_item_selector() builds a selector from the current loop value at runtime:
+ # URL path matching (a[href*="path-segment"]) or text matching (a:has-text("title")).
block_type = block.get("block_type")
- if is_in_for_loop and block_type == "file_download":
+ if is_in_for_loop and block_type in ("file_download", "navigation"):
body_stmts.append(
cst.parse_statement(
- 'await page.click(selector=context.download_selector(), prompt=context.prompt, ai="fallback")'
+ 'await page.click(selector=context.loop_item_selector(), prompt=context.prompt, ai="fallback")'
)
)
else:
diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.py
index b6a5f6961..ebe396d8d 100644
--- a/skyvern/core/script_generations/skyvern_page.py
+++ b/skyvern/core/script_generations/skyvern_page.py
@@ -3513,14 +3513,18 @@ class RunContext:
return ctx.loop_metadata.get("current_value")
return None
- def download_selector(self) -> str | None:
- """Build a CSS selector targeting a download link from the current loop value.
-
- Tries strategies in order of reliability:
- 1. URL in values → a[href*="filename.pdf"] (most precise)
- 2. Title text → a:has-text("title") (works when title IS the link)
-
- Returns the first viable selector, or None to fall back to AI.
+ def loop_item_selector(self) -> str | None:
+ """Build a CSS selector to click the current loop item's link on the page.
+
+ Strategies in order of reliability:
+ 1. URL path matching — extract the last meaningful path segment from URL
+ values and match via ``a[href*="path-segment"]``. Skips bare domains
+ (no path) to avoid matching every link on the page.
+ 2. Text matching — use the longest non-URL text value via
+ ``a:has-text("title")``.
+
+ Works for both navigation clicks and file downloads. Returns None when
+ no viable selector can be built (caller should fall back to AI).
"""
value = self.loop_value
if not value or not isinstance(value, dict):
@@ -3531,13 +3535,21 @@ class RunContext:
if not isinstance(v, str) or not v.strip():
continue
- # Strategy 1: URL-like values → href selector (most reliable)
- if re.match(r"https?://", v) or re.match(r"/.*\.\w+", v):
- filename = v.rstrip("/").rsplit("/", 1)[-1].split("?")[0]
- if filename and "." in filename:
- filename = re.sub(r'["\[\]\\]', "", filename)
- if filename:
- return f'a[href*="{filename}"]'
+ # Strategy 1: URL values → href selector from path segment.
+ # Uses the first URL with a viable path (dict insertion order is
+ # stable in Python 3.7+; extraction blocks control field ordering).
+ if re.match(r"https?://", v) or v.startswith("/"):
+ # Extract path, strip trailing slash
+ # "https://example.com/pub/water-act-2014/" → "/pub/water-act-2014"
+ # "/files/report.pdf?v=2" → "/files/report.pdf"
+ path = re.sub(r"https?://[^/]*", "", v).split("?")[0].split("#")[0].rstrip("/")
+ if path and path != "/":
+ segment = path.rsplit("/", 1)[-1]
+ segment = re.sub(r'["\[\]\\]', "", segment)
+ if segment and len(segment) >= 3:
+ return f'a[href*="{segment}"]'
+ # Short or empty path segment — fall through to text matching
+ continue
texts.append(v.strip())
@@ -3546,10 +3558,13 @@ class RunContext:
# Strategy 2: Direct link text match — many sites make the document
# title clickable (e.g., <a href="...">Annual Report 2025</a>).
- # Use the longest text (likely the title, which is more often the link text).
longest = max(texts, key=len)
- escaped = longest.replace('"', '\\"')
+ escaped = longest.replace("\n", " ").replace("\r", "").replace('"', '\\"')
if len(escaped) >= 3:
return f'a:has-text("{escaped}")'
return None
+
+ # Backward-compatible alias — existing cached scripts reference download_selector()
+ def download_selector(self) -> str | None:
+ return self.loop_item_selector()
diff --git a/skyvern/forge/prompts/skyvern/script-reviewer.j2 b/skyvern/forge/prompts/skyvern/script-reviewer.j2
index 714fe388b..afdeb1938 100644
--- a/skyvern/forge/prompts/skyvern/script-reviewer.j2
+++ b/skyvern/forge/prompts/skyvern/script-reviewer.j2
@@ -37,7 +37,7 @@ You are a script reviewer for a browser automation system. Your job is to update
```
10. **URL PATTERNS**: When different variants come from different URL hosts or paths, add `url_patterns` to the `page.classify()` call for FREE Tier-0 disambiguation. Use regex on the URL path: `url_patterns={"variant_a": "example\\.com/form-a"}`. URL patterns are checked BEFORE text patterns and cost nothing.
11. **FOR-LOOP BLOCKS**: When code runs inside a for-loop (e.g. by iterating over extracted items), every `page.click()`, `page.goto()`, or `page.download_file()` call MUST use per-iteration data to target the specific item. Never use a static selector or generic prompt that would resolve to the same element on every iteration.
- - **File download blocks**: Use `context.download_selector()` which builds a CSS selector (e.g. `a[href*="filename.pdf"]`) from URL-like fields in the current loop value. Combine with `context.prompt` for AI fallback: `await page.click(selector=context.download_selector(), prompt=context.prompt, ai="fallback")`. If `download_selector()` returns `None` (no URL in loop value), fall back to a text-based selector using `context.loop_value`.
+ - **File download and navigation blocks**: Use `context.loop_item_selector()` which builds a CSS selector from the current loop value — URL path matching (e.g. `a[href*="water-act-2014"]`) or text matching (e.g. `a:has-text("Document Title")`). Combine with `context.prompt` for AI fallback: `await page.click(selector=context.loop_item_selector(), prompt=context.prompt, ai="fallback")`. Returns `None` when no viable selector can be built, which makes `page.click` fall back to AI automatically.
- **Other blocks**: Use `context.loop_value` (dict) to build selectors. Prefer `page.goto(context.loop_value["url"])` for direct URLs, or include the item's title/identifier in the selector: `selector=f'a:has-text("{context.loop_value["title"]}")'`.
12. **NEVER HARDCODE PER-RUN VALUES IN SELECTORS OR PROMPTS**. If a selector or prompt contains a value that varies per run (a person's name, an ID, an address, a company name), it MUST be dynamic — never a literal string. This applies even when the page shows an abbreviated form (e.g., "J. Smith") that doesn't exactly match the parameter ("John H. Smith").
- **How to detect**: Check the **Current Run Parameter Values** and **Past Episode Parameters** sections below. If different episodes show different values for the same parameter (e.g., `full_name: "John Smith"` in one run, `full_name: "Jane Doe"` in another), any selector referencing that name is per-run and must be dynamic.
@@ -486,7 +486,7 @@ async def block_fn(page, context):
These properties are available on the `context` object when code runs inside a for-loop:
- `context.loop_value` — Current loop iteration value (dict). Contains the extracted data for this iteration (e.g. `{"title": "...", "download_url": "...", "unique_id": "..."}`).
- `context.prompt` — Per-iteration navigation goal/prompt (str or None). Set automatically from the block's navigation_goal with the current loop value substituted.
-- `context.download_selector()` — Builds a CSS selector targeting a download link from `context.loop_value`. Scans the dict values for URL-like strings, extracts the filename, and returns e.g. `'a[href*="filename.pdf"]'`. Returns `None` if no URL is found — in that case, build a selector manually from `context.loop_value`.
+- `context.loop_item_selector()` — Builds a CSS selector to click the current loop item's link. Tries URL path matching first (e.g. `'a[href*="water-act-2014"]'` from path segments), then text matching (e.g. `'a:has-text("Document Title")'`). Returns `None` if no viable selector — `page.click` will fall back to AI. Works for both navigation and download blocks.
### DO NOT USE (these do NOT exist and will crash at runtime)
- ~~`page.completed`~~ — Does NOT exist. Use `await page.complete()` to finish.
diff --git a/tests/unit/test_navigation_in_forloop_codegen.py b/tests/unit/test_navigation_in_forloop_codegen.py
new file mode 100644
index 000000000..ded5f8810
--- /dev/null
+++ b/tests/unit/test_navigation_in_forloop_codegen.py
@@ -0,0 +1,180 @@
+"""Tests for loop blocks using dynamic selectors via context.loop_item_selector().
+
+Validates that navigation and download blocks inside for-loops generate
+context.loop_item_selector()-based code instead of hardcoded xpaths
+from iteration 0's execution trace.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import libcst as cst
+
+from skyvern.core.script_generations.generate_script import _build_block_fn
+from skyvern.core.script_generations.skyvern_page import RunContext
+
+
+def _make_navigation_block(label: str = "navigate_to_page") -> dict:
+ return {
+ "label": label,
+ "block_type": "navigation",
+ "url": "https://example.com",
+ "navigation_goal": "Click on the document link",
+ }
+
+
+def _make_click_action() -> dict:
+ return {
+ "action_type": "click",
+ "xpath": "/html/body/div/a[3]",
+ "element_id": "elem_123",
+ "reasoning": "Click on target link",
+ }
+
+
+class TestNavigationInForLoopCodegen:
+ def test_navigation_in_loop_uses_loop_item_selector(self) -> None:
+ """Navigation blocks inside for-loops should use context.loop_item_selector()
+ instead of hardcoded xpath from iteration 0."""
+ block = _make_navigation_block()
+ actions = [_make_click_action()]
+
+ fn_def = _build_block_fn(block, actions, is_in_for_loop=True)
+ code = cst.Module(body=[fn_def]).code
+
+ assert "context.loop_item_selector()" in code
+ assert "context.prompt" in code
+ assert 'ai="fallback"' in code
+ # Should NOT contain the hardcoded xpath from the action
+ assert "xpath=" not in code
+
+ def test_navigation_outside_loop_uses_hardcoded_selectors(self) -> None:
+ """Navigation blocks NOT in a for-loop should still use action-based xpaths."""
+ block = _make_navigation_block()
+ actions = [_make_click_action()]
+
+ fn_def = _build_block_fn(block, actions, is_in_for_loop=False)
+ code = cst.Module(body=[fn_def]).code
+
+ # Should contain the hardcoded xpath from the action trace
+ assert "xpath=" in code
+ # Should NOT use dynamic selector
+ assert "loop_item_selector" not in code
+
+ def test_download_in_loop_uses_loop_item_selector(self) -> None:
+ """file_download blocks in loops should also use loop_item_selector()."""
+ block = {
+ "label": "download_files",
+ "block_type": "file_download",
+ "url": "https://example.com",
+ }
+ actions = [_make_click_action()]
+
+ fn_def = _build_block_fn(block, actions, is_in_for_loop=True)
+ code = cst.Module(body=[fn_def]).code
+
+ assert "context.loop_item_selector()" in code
+ assert "context.prompt" in code
+
+ def test_extraction_in_loop_not_affected(self) -> None:
+ """Extraction blocks in loops should NOT use download_selector (they extract data, not click links)."""
+ block = {
+ "label": "extract_documents",
+ "block_type": "extraction",
+ "data_extraction_goal": "Extract document titles",
+ }
+ actions = [
+ {
+ "action_type": "extract",
+ "data_extraction_goal": "Extract document titles",
+ "data": {"titles": ["doc1"]},
+ }
+ ]
+
+ fn_def = _build_block_fn(block, actions, is_in_for_loop=True)
+ code = cst.Module(body=[fn_def]).code
+
+ assert "loop_item_selector" not in code
+
+
+class TestLoopItemSelector:
+ """Direct unit tests for RunContext.loop_item_selector()."""
+
+ def test_url_path_without_extension(self) -> None:
+ """Relative paths like /reports/some-report-2024 should use href matching."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {"current_value": {"title": "Some Report", "uid": "/reports/some-report-2024"}}
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a[href*="some-report-2024"]'
+
+ def test_full_url_with_path(self) -> None:
+ """Full URLs should extract the last path segment."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {
+ "current_value": {"title": "Report", "url": "https://example.com/pub/annual-report-2025/"}
+ }
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a[href*="annual-report-2025"]'
+
+ def test_bare_domain_falls_to_text(self) -> None:
+ """URLs with no meaningful path should NOT produce href selectors."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {
+ "current_value": {"title": "Annual Report 2024", "url": "https://www.example.gov"}
+ }
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a:has-text("Annual Report 2024")'
+
+ def test_url_with_file_extension(self) -> None:
+ """URLs with file extensions should still work (path segment includes extension)."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {
+ "current_value": {"title": "Report", "url": "https://example.com/files/report.pdf"}
+ }
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a[href*="report.pdf"]'
+
+ def test_text_only_no_urls(self) -> None:
+ """Plain text values should use text matching."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {"current_value": {"title": "Quarterly Update", "uid": "quarterly"}}
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a:has-text("Quarterly Update")'
+
+ def test_percent_encoded_path_kept_as_is(self) -> None:
+ """Percent-encoded characters should be preserved — CSS a[href*=...] matches raw attribute values."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {
+ "current_value": {"title": "Report", "url": "https://example.com/files/Monthly%20Report%20Issue.pdf"}
+ }
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a[href*="Monthly%20Report%20Issue.pdf"]'
+
+ def test_short_path_segment_falls_to_text(self) -> None:
+ """URLs with short path segments (< 3 chars) should fall through to text matching."""
+ ctx = RunContext(parameters={}, page=MagicMock(), generated_parameters={})
+ mock_skyvern_ctx = MagicMock()
+ mock_skyvern_ctx.loop_metadata = {
+ "current_value": {"title": "Some Document", "url": "https://example.com/go/42"}
+ }
+ with patch("skyvern.core.script_generations.skyvern_page.skyvern_context") as mock_mod:
+ mock_mod.current.return_value = mock_skyvern_ctx
+ result = ctx.loop_item_selector()
+ assert result == 'a:has-text("Some Document")'