aboutsummaryrefslogtreecommitdiff
path: root/playwright-py/scripts/safe_actions.py
diff options
context:
space:
mode:
authorCraig Jennings <c@cjennings.net>2026-04-19 15:24:51 -0500
committerCraig Jennings <c@cjennings.net>2026-04-19 15:24:51 -0500
commit4ffa7417a359ef4eae09f61d7da4de06539462ca (patch)
treeb8eeb8aa5ec2344216c0f0cdcdcc82d0df307ce3 /playwright-py/scripts/safe_actions.py
parent11f5f003eef12bff9633ca8190e3c43c7dab6708 (diff)
downloadrulesets-4ffa7417a359ef4eae09f61d7da4de06539462ca.tar.gz
rulesets-4ffa7417a359ef4eae09f61d7da4de06539462ca.zip
refactor(playwright): split into playwright-js + playwright-py variants
Rename `playwright-skill/` → `playwright-js/` and add `playwright-py/` as a verbatim fork of Anthropic's official `webapp-testing` skill (Apache-2.0). Cross-pollinate: each skill gains patterns and helpers inspired by the other's strengths, with upstream semantics preserved. ## playwright-js (JS/TS stack) Renamed from playwright-skill; upstream lackeyjb MIT content untouched. New sections added (clearly marked, preserving upstream semantics): - Static HTML vs Dynamic Webapp decision tree (core Anthropic methodology) - Reconnaissance-Then-Action pattern (navigate → networkidle → inspect → act) - Console Log Capture snippet (page.on console/pageerror/requestfailed) Description updated to clarify JS/TS stack fit (React/Next/Vue/Svelte/Node) and reference `/playwright-py` as the Python sibling. ## playwright-py (Python stack) Verbatim fork of anthropics/skills/skills/webapp-testing; upstream SKILL.md and bundled `scripts/with_server.py` + examples kept intact. New scripts and examples added (all lackeyjb-style conveniences in Python): Scripts: scripts/detect_dev_servers.py Probe common localhost ports for HTTP servers; outputs JSON of found services. scripts/safe_actions.py safe_click, safe_type (retry-wrapped), handle_cookie_banner (common selectors), build_context_with_headers (env-var- driven: PW_HEADER_NAME / PW_HEADER_VALUE / PW_EXTRA_HEADERS='{…json…}'). Examples: examples/login_flow.py Login form + wait_for_url. examples/broken_links.py Scan visible external hrefs via HEAD. examples/responsive_sweep.py Multi-viewport screenshots to /tmp. SKILL.md gains 5 "Added:" sections documenting the new scripts, retry helpers, env-header injection, and /tmp script discipline. Attribution notes explicitly mark upstream vs local additions. ## Makefile SKILLS: playwright-skill → playwright-js + playwright-py deps target: extended Playwright step to install Python package + Chromium via `python3 -m pip install --user playwright && python3 -m playwright install chromium` when playwright-py/ is present. Idempotent (detected via `python3 -c "import playwright"`). ## Usage Both skills symlinked globally via `make install`. Invoke whichever matches the project stack — cross-references in descriptions route you to the right one. Run `make deps` once to install both runtimes.
Diffstat (limited to 'playwright-py/scripts/safe_actions.py')
-rw-r--r--playwright-py/scripts/safe_actions.py100
1 files changed, 100 insertions, 0 deletions
diff --git a/playwright-py/scripts/safe_actions.py b/playwright-py/scripts/safe_actions.py
new file mode 100644
index 0000000..c3f72bf
--- /dev/null
+++ b/playwright-py/scripts/safe_actions.py
@@ -0,0 +1,100 @@
+"""Retry-wrapped Playwright action helpers + common convenience utilities.
+
+Usage:
+ from scripts.safe_actions import (
+ safe_click, safe_type, handle_cookie_banner, build_context_with_headers
+ )
+"""
+
+import json
+import os
+import time
+
+
+def safe_click(page, selector, retries: int = 3, delay: float = 0.5, timeout: int = 5000):
+ """Click SELECTOR. Retry up to RETRIES times with DELAY seconds between.
+
+ Raises the last exception if all attempts fail.
+ """
+ last_err = None
+ for attempt in range(retries):
+ try:
+ page.wait_for_selector(selector, timeout=timeout)
+ page.click(selector)
+ return
+ except Exception as err:
+ last_err = err
+ if attempt < retries - 1:
+ time.sleep(delay)
+ raise last_err # type: ignore[misc]
+
+
+def safe_type(page, selector, value: str, retries: int = 3, delay: float = 0.5, timeout: int = 5000):
+ """Fill SELECTOR with VALUE. Retry on failure."""
+ last_err = None
+ for attempt in range(retries):
+ try:
+ page.wait_for_selector(selector, timeout=timeout)
+ page.fill(selector, value)
+ return
+ except Exception as err:
+ last_err = err
+ if attempt < retries - 1:
+ time.sleep(delay)
+ raise last_err # type: ignore[misc]
+
+
+def handle_cookie_banner(page, selectors=None) -> bool:
+ """Try common cookie-banner accept selectors; click the first that exists.
+
+ Returns True if a banner was found and clicked, False otherwise.
+ Does not raise on failure — many pages have no banner.
+ """
+ selectors = selectors or [
+ "#onetrust-accept-btn-handler",
+ 'button[aria-label*="ccept" i]',
+ 'button:has-text("Accept")',
+ 'button:has-text("I agree")',
+ 'button:has-text("Got it")',
+ '[data-testid="uc-accept-all-button"]',
+ "#cookie-accept",
+ ".cookie-accept",
+ ]
+ for selector in selectors:
+ try:
+ if page.locator(selector).count() > 0:
+ page.click(selector, timeout=1000)
+ return True
+ except Exception:
+ continue
+ return False
+
+
+def build_context_with_headers(browser, extra_kwargs=None):
+ """Create a browser context with extra HTTP headers from env vars.
+
+ Reads:
+ PW_HEADER_NAME / PW_HEADER_VALUE — single header
+ PW_EXTRA_HEADERS='{"X-A":"1","X-B":"2"}' — JSON object of headers
+
+ Unset env vars → plain context with no extra headers.
+ extra_kwargs, if supplied, are passed to browser.new_context().
+ """
+ headers: dict[str, str] = {}
+ name = os.environ.get("PW_HEADER_NAME")
+ value = os.environ.get("PW_HEADER_VALUE")
+ if name and value:
+ headers[name] = value
+ extra = os.environ.get("PW_EXTRA_HEADERS")
+ if extra:
+ try:
+ parsed = json.loads(extra)
+ if isinstance(parsed, dict):
+ headers.update({str(k): str(v) for k, v in parsed.items()})
+ except json.JSONDecodeError:
+ pass
+
+ kwargs: dict = dict(extra_kwargs or {})
+ if headers:
+ kwargs["extra_http_headers"] = headers
+ return browser.new_context(**kwargs)