🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
Python aiai-scrapingautomationcrawlercrawlingcrawling-pythondatadata-extractionmcpmcp-serverplaywrightpythonscrapingselectorsstealthweb-scraperweb-scrapingweb-scraping-pythonwebscrapingxpath
feat(mcp): Add tool to chain keyboard keys
Karim shoair3cc50aa9f3c3
diff --git a/agent-skill/Scrapling-Skill.zip b/agent-skill/Scrapling-Skill.zipindex 534c8e7..39bfb9b 100644Binary files a/agent-skill/Scrapling-Skill.zip and b/agent-skill/Scrapling-Skill.zip differdiff --git a/agent-skill/Scrapling-Skill/references/mcp-server.md b/agent-skill/Scrapling-Skill/references/mcp-server.mdindex 165a401..1b6c728 100644--- a/agent-skill/Scrapling-Skill/references/mcp-server.md+++ b/agent-skill/Scrapling-Skill/references/mcp-server.md@@ -1,8 +1,8 @@# Scrapling MCP Server-The Scrapling MCP server exposes eighteen tools over the MCP protocol. It supports CSS-selector-based content narrowing (reducing tokens by extracting only relevant elements before returning results), three levels of scraping capability (plain HTTP, browser-rendered, and stealth/anti-bot bypass), persistent browser session management, mouse actions, text input, and page screenshots returned as real image content blocks. Fetch tools come in two modes: one-shot tools (`browser_fetch_once`, `browser_fetch_many_once`, `browser_stealth_fetch_once`, `browser_stealth_fetch_many_once`) each launch and close their own browser, while `browser_fetch` and `session_make_request` work through sessions opened with `browser_open`/`open_request_session`.+The Scrapling MCP server exposes nineteen tools over the MCP protocol. It supports CSS-selector-based content narrowing (reducing tokens by extracting only relevant elements before returning results), three levels of scraping capability (plain HTTP, browser-rendered, and stealth/anti-bot bypass), persistent browser session management, mouse actions, text input, keyboard shortcuts, and page screenshots returned as real image content blocks. Fetch tools come in two modes: one-shot tools (`browser_fetch_once`, `browser_fetch_many_once`, `browser_stealth_fetch_once`, `browser_stealth_fetch_many_once`) each launch and close their own browser, while `browser_fetch` and `session_make_request` work through sessions opened with `browser_open`/`open_request_session`.-Fetch and HTTP request tools return a `ResponseModel` with fields: `status` (int), `content` (list of strings), `url` (str). Bulk tools return a list of these responses. The `browser_screenshot` tool returns a list of MCP content blocks: an `ImageContent` (the screenshot bytes) followed by a `TextContent` (the post-redirect URL). `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, and `browser_type` return plain text.+Fetch and HTTP request tools return a `ResponseModel` with fields: `status` (int), `content` (list of strings), `url` (str). Bulk tools return a list of these responses. The `browser_screenshot` tool returns a list of MCP content blocks: an `ImageContent` (the screenshot bytes) followed by a `TextContent` (the post-redirect URL). `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, and `browser_press_key` return plain text.## Shadow DOM@@ -235,6 +235,19 @@ Pass the exact snapshot reference value, such as `ref="e2"`. Take a new snapshotReturns `Text entered.` as plain text without echoing the text or taking a snapshot. Errors are not retried, and the page reservation is released after success, failure, or cancellation. Entry or submission may have already changed the page when an error occurs; use `browser_snapshot` to check before retrying.+### `browser_press_key` -- Chain keys and shortcuts at the current focus++Presses each item in order through native `page.keyboard.press` on the existing page in a dynamic or stealthy browser session. The page stays reserved for the full sequence. Call `browser_fetch` first. Use `browser_click` or `browser_type` to focus a control before pressing when needed; later presses follow any focus changes caused by earlier ones.++| Parameter | Type | Default | Description |+|-----------|------|---------|-------------|+| `session_id` | str | required | ID of an open browser session |+| `keys` | list[str] | required | Nonempty ordered list of nonempty native key names, characters, or shortcuts |++Use `["ControlOrMeta+A", "Backspace"]` to select all with the platform's modifier and then delete, or `["Tab", "Enter"]` to move focus and activate a control. Keep a shortcut in one item; separate items are separate presses. Use `["Escape"]` for one press; a space (`" "`) and plus (`"+"`) are valid list items. MCP validates the whole list and its string items before execution; the native API validates each key name or shortcut when pressed.++Returns `Keys pressed.` as plain text without an automatic snapshot or a wait for navigation. An error or cancellation stops the remaining presses; completed actions are not undone or retried. The page reservation is released after success, failure, or cancellation. Use `browser_snapshot` to check partial effects before retrying. Invalid keys, unknown or HTTP sessions, and missing, closed, or busy pages return an error.+### `session_make_request` -- HTTP request through an open requests sessionMakes an HTTP request (any method) through a session opened with `open_request_session`, reusing its cookies, connections, and browser fingerprint across calls. Same parameters as `make_request` plus a required `session_id`, minus the session-level `impersonate`, `proxy`, and `proxy_auth`. Raises on a browser session.@@ -292,6 +305,7 @@ Requires an open browser session. Call `browser_open` first, then pass the `sess| Scroll a page or nested panel | `browser_mouse_wheel` with `session_id` || Click by selector, snapshot ref, or coordinates | `browser_click` with `session_id` || Enter text by selector or snapshot ref | `browser_type` with `session_id` |+| Chain keys or keyboard shortcuts | `browser_press_key` with `session_id` |Start with `make_request` (fastest, lowest resource cost). Escalate to `browser_fetch_once` if content requires JS rendering. Escalate to `browser_stealth_fetch_once` only if blocked. For multiple pages from the same site, use a persistent session to avoid browser launch overhead.@@ -382,7 +396,7 @@ The MCP server name when registering with a client is `ScraplingServer`. The com## Connecting to remote browsers-`browser_open` doesn't have to launch a browser locally. Pass a `cdp_url` and it connects to an already-running browser through the Chrome DevTools Protocol, whether that browser is on the same machine, another host, or a managed browser provider. Both session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, and `browser_screenshot` as usual.+`browser_open` doesn't have to launch a browser locally. Pass a `cdp_url` and it connects to an already-running browser through the Chrome DevTools Protocol, whether that browser is on the same machine, another host, or a managed browser provider. Both session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, `browser_press_key`, and `browser_screenshot` as usual.The URL can be a WebSocket endpoint (`ws://`/`wss://`), which is what managed browser providers hand out, or the HTTP endpoint of a browser started with `--remote-debugging-port=9222`, reached as `cdp_url="http://localhost:9222"`.diff --git a/docs/ai/mcp-server.md b/docs/ai/mcp-server.mdindex b1b2480..04c47d0 100644--- a/docs/ai/mcp-server.md+++ b/docs/ai/mcp-server.md@@ -6,7 +6,7 @@ The **Scrapling MCP Server** is a new feature that brings Scrapling's powerful W## Features-The Scrapling MCP Server provides eighteen tools for web scraping and browser interaction, split into two modes: one-shot tools that each launch and close their own browser/client, and session tools that open a browser or an HTTP session once and then work through it.+The Scrapling MCP Server provides nineteen tools for web scraping and browser interaction, split into two modes: one-shot tools that each launch and close their own browser/client, and session tools that open a browser or an HTTP session once and then work through it.### One-shot tools@@ -47,9 +47,10 @@ The Scrapling MCP Server provides eighteen tools for web scraping and browser in- **`browser_mouse_wheel`**: Scroll pages, menus, and nested panels vertically or horizontally with the browser's native mouse wheel. Helps the AI explore long feeds and content that loads as you scroll. The AI can move the mouse first to choose a scrollable area.- **`browser_click`**: Click buttons, follow links, and use other page controls through selectors, snapshot references, or page coordinates. Supports left, right, and middle clicks, plus double-clicks.-#### Text Input+#### Text Input and Keyboard- **`browser_type`**: Fill search boxes, login fields, text areas, and other editable content through selectors or snapshot references. Replace or clear existing text, or type one character at a time for fields that react to key events. Can also press Enter to run a search or submit a form.+- **`browser_press_key`**: Chain keys and shortcuts on the current page to move between fields, submit forms, or dismiss menus in one call. Supports actions such as selecting all text and then deleting it, using the browser's current focus for each press.### Shadow DOM@@ -210,7 +211,7 @@ You can also set the `SCRAPLING_EXECUTABLE_PATH` environment variable before sta```Open a stealthy browser session on wss://cdp.provider.example/session/abc123, then use it to scrape the product details from https://shop.example.com. Close the session when you're done.```-Both browser session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, and `browser_screenshot` as usual.+Both browser session types (`dynamic` and `stealthy`) accept it, and the `session_id` you get back is used with `browser_fetch`, `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, `browser_press_key`, and `browser_screenshot` as usual.The URL can be a WebSocket endpoint (`ws://`/`wss://`), which is what managed browser providers hand out, or the HTTP endpoint of a browser you started yourself with the remote debugging port enabled:```commandlinediff --git a/docs/api-reference/mcp-server.md b/docs/api-reference/mcp-server.mdindex 47f2003..234dc18 100644--- a/docs/api-reference/mcp-server.md+++ b/docs/api-reference/mcp-server.md@@ -5,7 +5,7 @@ search:# MCP Server API Reference-The **Scrapling MCP Server** provides eighteen tools for web scraping and browser interaction through the Model Context Protocol (MCP). This server integrates Scrapling's capabilities directly into AI chatbots and agents, allowing conversational web scraping with advanced anti-bot bypass features.+The **Scrapling MCP Server** provides nineteen tools for web scraping and browser interaction through the Model Context Protocol (MCP). This server integrates Scrapling's capabilities directly into AI chatbots and agents, allowing conversational web scraping with advanced anti-bot bypass features.You can start the MCP server by running:@@ -30,7 +30,7 @@ server = ScraplingMCPServer(executable_path="/path/to/chromium")## Response Model-The standardized response structure returned by the fetch and HTTP request tools. Bulk tools return a list of these responses. Session management tools use the models below, `browser_screenshot` returns image and text content blocks, and `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, and `browser_type` return plain text.+The standardized response structure returned by the fetch and HTTP request tools. Bulk tools return a list of these responses. Session management tools use the models below, `browser_screenshot` returns image and text content blocks, and `browser_snapshot`, `browser_mouse_move`, `browser_mouse_wheel`, `browser_click`, `browser_type`, and `browser_press_key` return plain text.## ::: scrapling.core.ai.ResponseModelhandler: python@@ -61,6 +61,7 @@ The main MCP server class that provides all web scraping tools:- **`browser_mouse_wheel`**: Scroll pages and nested panels vertically or horizontally with native mouse wheel events. Works at the current pointer position, so mouse movement can choose the scrollable area.- **`browser_click`**: Click buttons, links, and other controls using selectors, snapshot references, or page coordinates. Supports left, right, and middle clicks, plus double-clicks.- **`browser_type`**: Fill search boxes, login fields, text areas, and other editable content through selectors or snapshot references. Supports replacing or clearing text, typing one character at a time for key events, and pressing Enter after entry.+- **`browser_press_key`**: Chain keys and shortcuts in one call to move between fields, submit forms, dismiss menus, or select and delete text. Each press uses the browser's current focus.- **`browser_fetch`**: Fetch a page through an open browser session and extract HTML, Markdown, text, or a structured snapshot. Snapshots can cover the whole page or a chosen element and include element references, positions, and sizes for later interaction.## ::: scrapling.core.ai.ScraplingMCPServerdiff --git a/scrapling/core/ai.py b/scrapling/core/ai.pyindex 24aad9a..0244c3c 100644--- a/scrapling/core/ai.py+++ b/scrapling/core/ai.py@@ -528,6 +528,19 @@ class ScraplingMCPServer:await locator.press("Enter", timeout=timeout)return "Text entered."+ async def browser_press_key(+ self, session_id: str, keys: Annotated[List[NonEmptyString], Field(min_length=1)]+ ) -> str:+ """Press keys or shortcuts in order at the current focus; stop on error and return plain text on success.++ :param session_id: ID from `browser_open`; call `browser_fetch` first.+ :param keys: Ordered presses, e.g. ["ControlOrMeta+A", "Backspace"] or ["Tab", "Enter"].+ """+ with self._browser_page(session_id) as (_, page):+ for key in keys:+ await page.keyboard.press(key)+ return "Keys pressed."+async def browser_screenshot(self,url: str,@@ -1376,6 +1389,13 @@ class ScraplingMCPServer:structured_output=False,annotations=_INPUT_TOOL_ANNOTATIONS,)+ server.add_tool(+ self.browser_press_key,+ title="Press keys",+ description=self.browser_press_key.__doc__,+ structured_output=False,+ annotations=_INPUT_TOOL_ANNOTATIONS,+ )# Screenshot tool (returns image + url content blocks, not structured JSON)server.add_tool(self.browser_screenshot,diff --git a/tests/ai/test_ai_mcp.py b/tests/ai/test_ai_mcp.pyindex b915893..1d28c83 100644--- a/tests/ai/test_ai_mcp.py+++ b/tests/ai/test_ai_mcp.py@@ -982,7 +982,7 @@ class TestServerToolRegistration:@pytest.mark.asyncioasync def test_tools_are_listed_with_expected_schemas(self):- """All 18 tools are advertised, with plain content for screenshots, snapshots, and input actions"""+ """All 19 tools are advertised, with plain content for screenshots, snapshots, and input actions"""server = ScraplingMCPServer()._build_server("127.0.0.1", 8000)async with Client(server) as client:assert client.instructions@@ -1001,13 +1001,14 @@ class TestServerToolRegistration:result = await client.call_tool(name, {})assert result.is_error- assert len(tools) == 18+ assert len(tools) == 19assert tools["browser_screenshot"].output_schema is Noneassert tools["browser_snapshot"].output_schema is Noneassert tools["browser_mouse_move"].output_schema is Noneassert tools["browser_click"].output_schema is Noneassert tools["browser_type"].output_schema is Noneassert tools["browser_mouse_wheel"].output_schema is None+ assert tools["browser_press_key"].output_schema is Noneassert {"session_snapshot","open_session",@@ -1037,6 +1038,7 @@ class TestServerToolRegistration:"browser_click","browser_type","browser_mouse_wheel",+ "browser_press_key",))@@ -1102,7 +1104,7 @@ class TestServerToolRegistration:assert result.ttl_ms == 3_600_000 and result.cache_scope == "public"annotations = {tool.name: tool.annotations for tool in result.tools if tool.annotations is not None}- assert len(annotations) == 18+ assert len(annotations) == 19for name in ("make_request","bulk_get",@@ -1123,7 +1125,7 @@ class TestServerToolRegistration:assert annotations[name].open_world_hint is Trueassert annotations["list_sessions"].read_only_hint is Trueassert annotations["list_sessions"].open_world_hint is False- for name in ("browser_mouse_move", "browser_click", "browser_type", "browser_mouse_wheel"):+ for name in ("browser_mouse_move", "browser_click", "browser_type", "browser_mouse_wheel", "browser_press_key"):assert annotations[name].read_only_hint is Falseassert annotations[name].destructive_hint is Trueassert annotations[name].idempotent_hint is Falsediff --git a/tests/ai/test_browser_press_key.py b/tests/ai/test_browser_press_key.pynew file mode 100644index 0000000..3456c47--- /dev/null+++ b/tests/ai/test_browser_press_key.py@@ -0,0 +1,242 @@+import asyncio+from contextlib import asynccontextmanager+from json import loads+from os import getenv+from unittest.mock import AsyncMock, Mock, call++import pytest+from anyio import CancelScope+from mcp.client import Client+from mcp.types import TextContent++from scrapling.core.ai import ScraplingMCPServer, SessionType, _SessionEntry+from scrapling.core._types import Any, AsyncGenerator+from scrapling.engines._browsers._base import AsyncSession+++HTML = """<!DOCTYPE html><html><body><form>+<label>First<input id="first" name="value"></label><label>Second<input id="second"></label>+<button>Save</button></form><output id="submitted" data-count="0"></output><output id="escaped"></output>+<textarea id="events" hidden>[]</textarea><script>+document.querySelector('form').addEventListener('submit', event => {+ event.preventDefault();+ const output = document.querySelector('#submitted');+ output.textContent = new FormData(event.target).get('value');+ output.dataset.count = Number(output.dataset.count) + 1;+});+for (const type of ['keydown', 'keyup']) {+ document.addEventListener(type, event => {+ const events = document.querySelector('#events');+ events.value = JSON.stringify([...JSON.parse(events.value), {type, key: event.key, trusted: event.isTrusted,+ target: event.target.id, ctrl: event.ctrlKey, meta: event.metaKey, shift: event.shiftKey, alt: event.altKey}]);+ if (type === 'keydown' && event.key === 'Escape') document.querySelector('#escaped').textContent = 'closed';+ });+}+</script></body></html>"""+++def _server(session_type: SessionType = "dynamic") -> tuple[ScraplingMCPServer, AsyncSession, Mock]:+ server = ScraplingMCPServer()+ session = AsyncSession()+ session._is_alive = True+ page = Mock()+ page.is_closed.return_value = False+ page.keyboard.press = AsyncMock()+ session.page_pool.add_page(page).mark_ready()+ server._sessions["browser"] = _SessionEntry(session, session_type)+ return server, session, page+++async def test_browser_press_key_schema() -> None:+ async with Client(ScraplingMCPServer()._build_server("127.0.0.1", 8000)) as client:+ tool = next(tool for tool in (await client.list_tools()).tools if tool.name == "browser_press_key")+ assert tool.title == "Press keys"+ assert set(tool.input_schema["properties"]) == {"session_id", "keys"}+ assert tool.input_schema["required"] == ["session_id", "keys"]+ keys = tool.input_schema["properties"]["keys"]+ assert keys["type"] == "array" and keys["minItems"] == 1+ assert keys["items"]["type"] == "string" and keys["items"]["minLength"] == 1++[email protected]("keys", [["Enter"], ["Escape", "Shift+Tab", "ControlOrMeta+A", "+", " ", "Enter", "Enter"]])+async def test_browser_press_key_forwards_native_keys_in_order(keys: list[str]) -> None:+ server, session, page = _server()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", "keys": keys})+ assert not result.is_error+ assert result.structured_content is None+ assert result.content == [TextContent(type="text", text="Keys pressed.")]+ assert page.keyboard.press.await_args_list == [call(key) for key in keys]+ page.locator.assert_not_called()+ page.aria_snapshot.assert_not_called()+ page.screenshot.assert_not_called()+ assert session.page_pool.pages[0].state == "ready"+++ "values",+ [+ {},+ {"key": "Enter"},+ {"keys": []},+ {"keys": "Enter"},+ {"keys": None},+ {"keys": ["Enter", ""]},+ {"keys": ["Enter", None]},+ {"keys": ["Enter", 42]},+ {"keys": ["Enter", ["Escape"]]},+ ],+)+async def test_browser_press_key_invalid_input_does_not_reserve_page(values: dict[str, Any]) -> None:+ server, session, page = _server()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", **values})+ assert result.is_error+ page.is_closed.assert_not_called()+ page.keyboard.press.assert_not_awaited()+ assert session.page_pool.pages[0].state == "ready"+++ "state, message", [("missing", "not found"), ("static", "'static'"), ("empty", "browser_fetch")]+)+async def test_browser_press_key_session_errors_reach_mcp(state: str, message: str) -> None:+ server, session, page = _server("static" if state == "static" else "dynamic")+ if state == "missing":+ server._sessions.clear()+ elif state == "empty":+ session.page_pool.clear()+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", "keys": ["Enter"]})+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert message in result.content[0].text+ page.keyboard.press.assert_not_awaited()+++async def test_browser_press_key_error_stops_remaining_keys_and_releases_page() -> None:+ server, session, page = _server()+ page.keyboard.press.side_effect = [None, RuntimeError("key failed")]+ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", "keys": ["a", "Bad", "Enter"]})+ assert result.is_error+ assert result.content and isinstance(result.content[0], TextContent)+ assert "key failed" in result.content[0].text+ assert page.keyboard.press.await_args_list == [call("a"), call("Bad")]+ assert session.page_pool.pages[0].state == "ready"+ page.keyboard.press.side_effect = None+ assert await server.browser_press_key("browser", ["Escape"]) == "Keys pressed."++[email protected]("cancel_mode", ["task", "scope"])+async def test_browser_press_key_reserves_page_until_cancelled(cancel_mode: str) -> None:+ server, session, page = _server()+ entered = asyncio.Event()+ scope = CancelScope()++ async def pending(key: str) -> None:+ if key == "Enter":+ entered.set()+ await asyncio.Event().wait()++ async def press() -> None:+ with scope:+ await server.browser_press_key("browser", ["a", "Enter", "Escape"])++ page.keyboard.press.side_effect = pending+ task = asyncio.create_task(press())+ try:+ await asyncio.wait_for(entered.wait(), 5)+ assert session.page_pool.pages[0].state == "busy"+ with pytest.raises(RuntimeError, match="busy"):+ await server.browser_press_key("browser", ["Enter"])+ finally:+ scope.cancel() if cancel_mode == "scope" else task.cancel()+ if cancel_mode == "scope":+ await asyncio.wait_for(task, 5)+ assert scope.cancelled_caught+ else:+ with pytest.raises(asyncio.CancelledError):+ await task+ assert page.keyboard.press.await_args_list == [call("a"), call("Enter")]+ assert session.page_pool.pages[0].state == "ready"+++@asynccontextmanager+async def _browser(session_type: SessionType) -> AsyncGenerator[tuple[Client, Any, Any], None]:+ server = ScraplingMCPServer(executable_path=getenv("SCRAPLING_EXECUTABLE_PATH"))++ async def serve(route: Any) -> None:+ await route.fulfill(status=200, content_type="text/html", body=HTML)++ async with Client(server._build_server("127.0.0.1", 8000)) as client:+ opened = await client.call_tool("browser_open", {"session_type": session_type, "session_id": "browser"})+ assert not opened.is_error+ try:+ session = server._sessions["browser"].session+ await session.context.route("**/*", serve)+ fetched = await client.call_tool(+ "browser_fetch", {"session_id": "browser", "url": "https://keys.test/", "google_search": False}+ )+ assert not fetched.is_error+ yield client, session, session.page_pool.pages[0].page+ finally:+ closed = await client.call_tool("close_session", {"session_id": "browser"})+ assert not closed.is_error++[email protected]("session_type", ["dynamic", "stealthy"])+async def test_browser_press_key_live_focus_editing_and_shortcuts(session_type: SessionType) -> None:+ async with _browser(session_type) as (client, session, page):++ async def press(keys: list[str]) -> None:+ result = await client.call_tool("browser_press_key", {"session_id": "browser", "keys": keys})+ assert not result.is_error+ assert session.page_pool.pages[0].state == "ready"++ typed = await client.call_tool(+ "browser_type", {"session_id": "browser", "selector": "#first", "text": "initial"}+ )+ assert not typed.is_error+ await page.locator("#events").evaluate("element => element.value = '[]'")+ await press(["Tab", "z", "Shift+Tab"])+ await page.wait_for_function("document.activeElement.id === 'first'", timeout=5000)+ assert await page.locator("#second").input_value() == "z"+ assert await page.locator("#first").input_value() == "initial"+ await press(["ControlOrMeta+A", "Backspace"])+ assert await page.locator("#first").input_value() == ""+ await press(["a", " ", "+", "ArrowLeft", "b"])+ assert await page.locator("#first").input_value() == "a b+"+ await press(["Escape", "Enter"])+ await page.wait_for_function("document.querySelector('#escaped').textContent === 'closed'", timeout=5000)+ await page.wait_for_function("document.querySelector('#submitted').dataset.count === '1'", timeout=5000)+ assert await page.locator("#submitted").inner_text() == "a b+"+ invalid = await client.call_tool(+ "browser_press_key", {"session_id": "browser", "keys": ["c", "ScraplingInvalidKey", "x"]}+ )+ assert invalid.is_error+ assert invalid.content and isinstance(invalid.content[0], TextContent)+ assert "Unknown key" in invalid.content[0].text+ assert session.page_pool.pages[0].state == "ready"+ assert await page.locator("#first").input_value() == "a bc+"+ await press(["d"])+ assert await page.locator("#first").input_value() == "a bcd+"+ events = loads(await page.locator("#events").input_value())+ assert events and all(event["trusted"] for event in events)+ assert [event["shift"] for event in events if event["type"] == "keydown" and event["key"] == "Tab"] == [+ False,+ True,+ ]+ assert any(event["type"] == "keydown" and (event["ctrl"] or event["meta"]) for event in events)+ assert not any(event["key"] in ("ScraplingInvalidKey", "x") for event in events)+ for key in ("Backspace", "b", "c", "d", "Escape", "Enter"):+ keyed = [event for event in events if event["key"] == key]+ assert [event["type"] for event in keyed] == ["keydown", "keyup"]+ assert all(not any(event[modifier] for modifier in ("ctrl", "meta", "shift", "alt")) for event in keyed)