### Install CDP-Patches from PyPI Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/README.md Installs the cdp-patches library using pip. This is the standard installation method for basic usage. ```bash pip install cdp-patches ``` -------------------------------- ### Install CDP-Patches with Full Linting Support Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/README.md Installs cdp-patches with the 'automation_linting' extra, which includes dependencies for Playwright, BotRight, Selenium, and Selenium-Driverless for comprehensive linting capabilities. ```bash pip install cdp-patches[automation_linting] ``` -------------------------------- ### Install CDP Patches Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Instructions for installing the CDP Patches library using pip. Includes an option for development with full linting support for all automation frameworks. ```bash pip install cdp-patches pip install cdp-patches[automation_linting] ``` -------------------------------- ### Synchronous Selenium Click with cdp-patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/selenium-usage.md This Python snippet shows how to perform a synchronous click action on a web element using Selenium WebDriver and the SyncInput class from cdp-patches. It includes helper functions to get element coordinates and configures Chrome options to disable logging and automation. ```python from selenium import webdriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.by import By from cdp_patches.input import SyncInput # Locator Position Helper def get_locator_pos(locator: WebElement): location = locator.location size = locator.size assert location, size x, y, width, height = location.get("x"), location.get("y"), size.get("width"), size.get("height") assert x and y and width and height x, y = x + width // 2, y + height // 2 return x, y options = webdriver.ChromeOptions() # disable logs & automation options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"]) options.add_experimental_option("useAutomationExtension", False) options.add_argument("--log-level=3") with webdriver.Chrome(...) as driver: sync_input = SyncInput(browser=driver) # Example: Click Button # Find Button Coords locator = driver.find_element(By.XPATH, "//button") x, y = get_locator_pos(locator) # Click Coords => Click Button sync_input.click("left", x, y) ``` -------------------------------- ### Playwright Integration with CDP Patches (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Provides a complete example of integrating CDP Patches with Playwright for both synchronous and asynchronous operations. It demonstrates initializing `SyncInput` with a Playwright browser or context, locating elements, and performing actions like clicking and typing using CDP Patches for undetectable input simulation. ```python # Sync Playwright Example from playwright.sync_api import sync_playwright, Locator from cdp_patches.input import SyncInput def get_locator_pos(locator: Locator): """Get center coordinates of a Playwright locator.""" bounding_box = locator.bounding_box() assert bounding_box x = bounding_box["x"] + bounding_box["width"] // 2 y = bounding_box["y"] + bounding_box["height"] // 2 return x, y with sync_playwright() as playwright: browser = playwright.chromium.launch(headless=False) # Must be headful context = browser.new_context() page = context.new_page() # Initialize CDP Patches with browser or context sync_input = SyncInput(browser=browser) # or SyncInput(browser=context) page.goto("https://example.com") # Click a button using undetectable OS-level input button = page.locator("button#submit") x, y = get_locator_pos(button) sync_input.click("left", x, y) # Type into an input field input_field = page.locator("input#username") x, y = get_locator_pos(input_field) sync_input.click("left", x, y) sync_input.type("my_username") browser.close() ``` -------------------------------- ### Asynchronous Selenium Click with cdp-patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/selenium-usage.md This Python snippet demonstrates an asynchronous click action using Selenium-driverless and the AsyncInput class from cdp-patches. It utilizes asyncio for non-blocking operations and retrieves element coordinates using the `mid_location` method. ```python import asyncio from selenium_driverless import webdriver from selenium_driverless.types.by import By from cdp_patches.input import AsyncInput async def main(): async with webdriver.Chrome(...) as driver: async_input = await AsyncInput(browser=driver) # Example: Click Button # Find Button Coords locator = await driver.find_element(By.XPATH, "//button") x, y = await locator.mid_location() # Click Coords => Click Button await async_input.click("left", x, y) asyncio.run(main()) ``` -------------------------------- ### Control Mouse Press/Release with down() and up() Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Explains the `down()` and `up()` methods for granular control over mouse button press and release events. These are useful for drag-and-drop operations and custom click sequences, with an example of a drag operation. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(browser=browser) # Mouse button down at coordinates sync_input.down("left", 100, 200) # Mouse button up at same coordinates (complete click) sync_input.up("left", 100, 200) # Drag operation: down at start, up at end sync_input.down("left", 100, 100) sync_input.move(300, 300) sync_input.up("left", 300, 300) ``` -------------------------------- ### Async Playwright: Get Locator Position and Click Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates how to get the center coordinates of a Playwright locator and then use CDP Patches' AsyncInput to click at those coordinates. This requires the playwright library and cdp_patches.input. ```python import asyncio from playwright.async_api import async_playwright, Locator from cdp_patches.input import AsyncInput async def get_locator_pos(locator: Locator): """Get center coordinates of a Playwright locator.""" bounding_box = await locator.bounding_box() assert bounding_box x = bounding_box["x"] + bounding_box["width"] // 2 y = bounding_box["y"] + bounding_box["height"] // 2 return x, y async def main(): async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=False) page = await browser.new_page() async_input = await AsyncInput(browser=browser) await page.goto("https://example.com") button = page.locator("button#submit") x, y = await get_locator_pos(button) await async_input.click("left", x, y) await browser.close() asyncio.run(main()) ``` -------------------------------- ### Perform Double Clicks with double_click() Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Illustrates the `double_click()` method for performing double-clicks. It supports different mouse buttons, modifier keys, disabling behavior emulation, and includes both synchronous and asynchronous usage examples. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(browser=browser) # Double left click sync_input.double_click("left", 100, 200) # Double right click sync_input.double_click("right", 150, 250) # Double click with modifier sync_input.double_click("left", 100, 200, pressed="shift") # Without behavior emulation (instant positioning) sync_input.double_click("left", 100, 200, emulate_behaviour=False) # Async version # await async_input.double_click("left", 100, 200) ``` -------------------------------- ### Selenium: Get Element Center and Click/Type Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Shows how to integrate CDP Patches' SyncInput with a standard Selenium WebDriver. It includes getting the center coordinates of a WebElement and then using SyncInput to click and type. Dependencies include selenium and cdp_patches.input. ```python from selenium import webdriver from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver.common.by import By from cdp_patches.input import SyncInput def get_element_center(element: WebElement): """Get center coordinates of a Selenium WebElement.""" location = element.location size = element.size x = location["x"] + size["width"] // 2 y = location["y"] + size["height"] // 2 return x, y # Configure Chrome options options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["enable-logging", "enable-automation"]) options.add_experimental_option("useAutomationExtension", False) options.add_argument("--log-level=3") with webdriver.Chrome(options=options) as driver: # Initialize CDP Patches with Selenium driver sync_input = SyncInput(browser=driver) driver.get("https://example.com") # Find and click element button = driver.find_element(By.XPATH, "//button[@id='submit']") x, y = get_element_center(button) sync_input.click("left", x, y) # Find input and type input_field = driver.find_element(By.ID, "username") x, y = get_element_center(input_field) sync_input.click("left", x, y) sync_input.type("my_username") ``` -------------------------------- ### KeyboardCodes Constants for Special Keys (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Lists the available `KeyboardCodes` constants for simulating special key presses. These codes are platform-agnostic and automatically adapt to the operating system. Examples include navigation, function, and modifier keys. ```python from cdp_patches.input import KeyboardCodes, WinKeyboardCodes, LinuxKeyboardCodes # Use platform-agnostic KeyboardCodes (auto-selects based on OS) KeyboardCodes.ENTER # Enter/Return key KeyboardCodes.TAB # Tab key KeyboardCodes.BACKSPACE # Backspace key KeyboardCodes.DELETE # Delete key KeyboardCodes.ESCAPE # Escape key KeyboardCodes.SPACE # Space key # Arrow keys KeyboardCodes.LEFT_ARROW KeyboardCodes.RIGHT_ARROW KeyboardCodes.UP_ARROW KeyboardCodes.DOWN_ARROW # Navigation keys KeyboardCodes.HOME KeyboardCodes.END KeyboardCodes.PAGE_UP KeyboardCodes.PAGE_DOWN # Function keys KeyboardCodes.F1 KeyboardCodes.F2 # ... through F24 # Modifier keys KeyboardCodes.CONTROL KeyboardCodes.SHIFT KeyboardCodes.ALT # Platform-specific codes if needed # Windows format: "{ENTER}", "{TAB}", "{VK_CONTROL}" # Linux format: "<>", "<>", "<>" ``` -------------------------------- ### Initialize SyncInput Class Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates how to initialize the synchronous `SyncInput` class. It can be initialized with a browser instance or a process ID. Optional parameters for scale factor, behavior emulation, and window timeout are also shown. ```python from cdp_patches.input import SyncInput # Initialize with a browser instance (recommended) sync_input = SyncInput(browser=browser) # Or initialize with a process ID directly sync_input = SyncInput(pid=12345) # Optional parameters sync_input = SyncInput( browser=browser, scale_factor=1.0, # Display scale factor (auto-detected if browser provided) emulate_behaviour=True, # Enable human-like mouse movements window_timeout=30.0 # Timeout for finding browser window ) # Access properties print(sync_input.scale_factor) # Get current scale factor print(sync_input.pid) # Get browser process ID ``` -------------------------------- ### Initialize AsyncInput Class Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Shows how to initialize the asynchronous `AsyncInput` class for use with async frameworks. Initialization can be done with a browser instance or process ID, using `await`. Optional parameters are similar to `SyncInput`. ```python import asyncio from cdp_patches.input import AsyncInput async def main(): # Initialize with await syntax async_input = await AsyncInput(browser=browser) # Or with process ID async_input = await AsyncInput(pid=12345) # Optional parameters async_input = await AsyncInput( browser=browser, scale_factor=1.0, emulate_behaviour=True, window_timeout=30.0 ) # Use async input methods await async_input.click("left", 100, 200) asyncio.run(main()) ``` -------------------------------- ### Synchronous Input Dispatching with CDP-Patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/README.md Demonstrates synchronous input dispatching using the SyncInput class from cdp_patches.input. It allows for actions like clicks, mouse movements, typing, and scrolling by either process ID (pid) or a browser instance. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(pid=pid) # Or sync_input = SyncInput(browser=browser) # Dispatch Inputs sync_input.click("left", 100, 100) # Left click at (100, 100) sync_input.double_click("left", 100, 100) # Left double-click at (100, 100) sync_input.down("left", 100, 100) # Left mouse button down at (100, 100) sync_input.up("left", 100, 100) # Left mouse button up at (100, 100) sync_input.move(100, 100) # Move mouse to (100, 100) sync_input.scroll("down", 10) # Scroll down by 10 lines sync_input.type("Hello World!") # Type "Hello World!" ``` -------------------------------- ### Initialize AsyncInput Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/async-usage.md Initializes an AsyncInput instance to interact with a browser window. It can connect to a specific Chrome PID or an existing browser instance (Selenium-driverless or Playwright). Optional parameters control scaling, emulation behavior, and window recognition timeouts. ```python from cdp_patches.input import AsyncInput # Example using PID async_input_by_pid = AsyncInput(pid=12345) # Example using Selenium-driverless browser instance # Assuming 'sd_browser' is an initialized selenium_driverless Chrome instance # async_input_by_browser = AsyncInput(browser=sd_browser) # Example using Playwright async browser instance # Assuming 'pw_browser' is an initialized Playwright async browser instance # async_input_by_pw = AsyncInput(browser=pw_browser, scale_factor=1.5, emulate_behaviour=False) ``` -------------------------------- ### Simulate Mouse Down/Up Events with Modifier Keys (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates simulating mouse down and up events using the `sync_input` object. It shows how to include modifier keys like 'ctrl' during these events. The `emulate_behaviour=False` option disables pre-event movement simulation. ```python sync_input.down("left", 100, 200, pressed="ctrl") sync_input.up("left", 100, 200, pressed="ctrl") sync_input.down("left", 100, 200, emulate_behaviour=False) ``` -------------------------------- ### Simulate Async Mouse Down/Up Events (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Shows the asynchronous versions of simulating mouse down and up events using `async_input`. These functions are `await`-ed and are suitable for non-blocking operations in asynchronous Python code. ```python await async_input.down("left", 100, 200) await async_input.up("left", 100, 200) ``` -------------------------------- ### Simulate Mouse Clicks and Movements Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/sync-usage.md This section covers methods for simulating mouse actions. `click` and `double_click` perform the respective actions at specified coordinates. `down` and `up` simulate mouse button press and release. `move` allows for simulating mouse cursor movement. These methods can optionally emulate human-like behavior and have configurable timeouts. ```python # Type Abbreviations from typing import Union, Literal, Optional Pos = Union[int, float] Button = Literal["left", "right", "middle"] EmulateBehaviour: Optional[bool] = True Timeout: Optional[float] = None # Assuming sync_input is an instance of SyncInput # sync_input.click(button="left", x=100, y=200, emulate_behaviour=True, timeout=5.0) # sync_input.double_click(button="left", x=150, y=250, emulate_behaviour=True, timeout=5.0) # sync_input.down(button="right", x=50, y=50, emulate_behaviour=True, timeout=5.0) # sync_input.up(button="right", x=50, y=50) # sync_input.move(x=300, y=400, emulate_behaviour=True, timeout=5.0) ``` -------------------------------- ### Simulate Typing Actions Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/sync-usage.md The `type_text` method simulates typing text into an input field. It accepts the text to be typed and an optional `emulate_behaviour` flag. The typing speed can be configured via the `typing_speed` property of the SyncInput instance. ```python # Assuming sync_input is an instance of SyncInput # sync_input.typing_speed = 60 # Set typing speed to 60 WPM # sync_input.type_text(text="Hello, world!", emulate_behaviour=True) ``` -------------------------------- ### Selenium-Driverless: Async Click and Type Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Illustrates using CDP Patches' AsyncInput with the async Selenium-Driverless library. It leverages the built-in `mid_location` helper for element positioning. Requires selenium-driverless and cdp_patches.input. ```python import asyncio from selenium_driverless import webdriver from selenium_driverless.types.by import By from cdp_patches.input import AsyncInput async def main(): async with webdriver.Chrome() as driver: # Initialize CDP Patches with async driver async_input = await AsyncInput(browser=driver) await driver.get("https://example.com") # Find element and get position using driverless helper button = await driver.find_element(By.XPATH, "//button[@id='submit']") x, y = await button.mid_location() # Built-in center position helper await async_input.click("left", x, y) # Type into input input_field = await driver.find_element(By.ID, "username") x, y = await input_field.mid_location() await async_input.click("left", x, y) await async_input.type("my_username") asyncio.run(main()) ``` -------------------------------- ### Initialize SyncInput for Browser Interaction Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/sync-usage.md The SyncInput class is used to interact with browser elements. It can be initialized with a process ID (PID) of the Chrome browser or a browser instance from libraries like Selenium or Playwright. Optional parameters control scaling factor, emulation of human behavior, and window recognition timeouts. ```python from cdp_patches.input import SyncInput # Initialize with PID sync_input_pid = SyncInput(pid=12345) # Initialize with a Selenium WebDriver instance # from selenium import webdriver # driver = webdriver.Chrome() # sync_input_selenium = SyncInput(browser=driver) # Initialize with a Playwright browser instance # from playwright.sync_api import sync_playwright # p = sync_playwright().start() # playwright_browser = p.chromium.launch() # sync_input_playwright = SyncInput(browser=playwright_browser) ``` -------------------------------- ### Asynchronous Input Dispatching with CDP-Patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/README.md Illustrates asynchronous input dispatching using the AsyncInput class from cdp_patches.input. This is suitable for non-blocking operations and requires an asyncio event loop. Inputs can be dispatched via process ID (pid) or a browser instance. ```python import asyncio from cdp_patches.input import AsyncInput async def main(): async_input = await AsyncInput(pid=pid) # Or async_input = await AsyncInput(browser=browser) # Dispatch Inputs await async_input.click("left", 100, 100) # Left click at (100, 100) await async_input.double_click("left", 100, 100) # Left double-click at (100, 100) await async_input.down("left", 100, 100) # Left mouse button down at (100, 100) await async_input.up("left", 100, 100) # Left mouse button up at (100, 100) await async_input.move(100, 100) # Move mouse to (100, 100) await async_input.scroll("down", 10) # Scroll down by 10 lines await async_input.type("Hello World!") # Type "Hello World!" if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Perform Mouse Clicks with click() Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates the `click()` method for performing mouse clicks. It supports different buttons (left, right, middle), modifier keys, disabling behavior emulation, custom timeouts, and has both synchronous and asynchronous versions. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(browser=browser) # Left click at coordinates (100, 200) sync_input.click("left", 100, 200) # Right click sync_input.click("right", 150, 250) # Middle click sync_input.click("middle", 200, 300) # Click with modifier keys held (e.g., Ctrl+Click) sync_input.click("left", 100, 200, pressed="ctrl") # Click without human-like mouse movement sync_input.click("left", 100, 200, emulate_behaviour=False) # Custom timeout between mouse down and up sync_input.click("left", 100, 200, timeout=0.1) # Async version # await async_input.click("left", 100, 200) ``` -------------------------------- ### AsyncInput Mouse Click Methods Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/async-usage.md Provides methods for performing mouse clicks asynchronously. These include single clicks, double clicks, mouse down, mouse up, and mouse movement. Parameters allow specifying the button, coordinates, emulation behavior, and timeouts. ```python from typing import Union, Literal, Optional Pos = Union[int, float] Button = Literal["left", "right", "middle"] EmulateBehaviour: Optional[bool] = True Timeout: Optional[float] = None # Assuming 'async_input' is an initialized AsyncInput instance # Click at coordinates (100, 200) with the left button # await async_input.click(button="left", x=100, y=200, emulate_behaviour=True, timeout=10.0) # Double-click at coordinates (300, 400) with the middle button # await async_input.double_click(button="middle", x=300, y=400, emulate_behaviour=False, timeout=5.0) # Mouse down at coordinates (50, 50) # await async_input.down(button="left", x=50, y=50, emulate_behaviour=True, timeout=5.0) # Mouse up at coordinates (50, 50) # await async_input.up(button="left", x=50, y=50) # Move mouse to coordinates (600, 700) # await async_input.move(x=600, y=700, emulate_behaviour=True, timeout=2.0) ``` -------------------------------- ### CDP Patches: Handle WindowClosedException Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates how to catch and handle the `WindowClosedException` from CDP Patches when interacting with a browser that has been closed. This is crucial for robust error management. Requires cdp_patches.input and cdp_patches.input.exceptions. ```python from cdp_patches.input import SyncInput from cdp_patches.input.exceptions import WindowClosedException sync_input = SyncInput(browser=browser) try: sync_input.click("left", 100, 200) except WindowClosedException as e: print(f"Browser window was closed: {e}") # Handle gracefully - perhaps restart browser # The exception includes the process ID if available try: sync_input.move(300, 400) except WindowClosedException as e: # e.args contains the message with PID info print(f"Window closed: {e}") ``` -------------------------------- ### Type Text with CDP Patches (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Explains the `type` method for simulating keyboard input. It supports typing text with natural timing variations, instant filling (`fill=True`), custom delays between characters (`timeout`), and typing special keys using `KeyboardCodes`. It also shows how to combine text input with special key presses. ```python from cdp_patches.input import SyncInput, KeyboardCodes sync_input = SyncInput(browser=browser) # Type text with human-like timing sync_input.type("Hello World!") # Type text instantly (fill mode) sync_input.type("Hello World!", fill=True) # Custom typing speed via timeout between characters sync_input.type("Hello World!", timeout=0.02) # Type special keys using KeyboardCodes sync_input.type(KeyboardCodes.ENTER) sync_input.type(KeyboardCodes.TAB) sync_input.type(KeyboardCodes.BACKSPACE) # Combine text with special keys sync_input.type("username") sync_input.type(KeyboardCodes.TAB) sync_input.type("password") sync_input.type(KeyboardCodes.ENTER) # Async version await async_input.type("Hello World!") ``` -------------------------------- ### Simulate Scrolling Actions Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/sync-usage.md The `scroll` method allows for simulating page scrolling within the browser. It takes a direction ('up', 'down', 'left', 'right') and an amount to scroll by. This is useful for navigating content that extends beyond the viewport. ```python # Assuming sync_input is an instance of SyncInput # sync_input.scroll(direction="down", amount=500) # sync_input.scroll(direction="right", amount=300) ``` -------------------------------- ### Move Mouse Cursor with CDP Patches (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Illustrates the `move` method for repositioning the mouse cursor. It supports human-like curved trajectories via Bézier curves (default), instant jumps (`emulate_behaviour=False`), holding modifier keys during movement, and custom movement speed adjustments using `timeout`. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(browser=browser) # Move mouse to coordinates with human-like trajectory sync_input.move(500, 300) # Move without trajectory emulation (instant jump) sync_input.move(500, 300, emulate_behaviour=False) # Move with modifier key held (for hover with key pressed) sync_input.move(500, 300, pressed="shift") # Custom movement speed (timeout between trajectory points) sync_input.move(500, 300, timeout=0.005) # Track last position print(f"Last position: ({sync_input.last_x}, {sync_input.last_y})") # Async version await async_input.move(500, 300) ``` -------------------------------- ### Type Text into Input Field (Python) Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/sync-usage.md The sync_input.type function simulates typing text into an input field. It accepts the text to be typed, an optional boolean to indicate if the input field should be filled (cleared and then typed into), and a timeout object to control the duration of the operation. This function is useful for automating form submissions or interactive text-based interfaces. ```python sync_input.type(text: str, fill: Optional[bool] = False, timeout: Timeout) ``` -------------------------------- ### Scroll Page Content with CDP Patches (Python) Source: https://context7.com/kaliiiiiiiiii-vinyzu/cdp-patches/llms.txt Demonstrates the `scroll` method for simulating page scrolling. It allows scrolling in specified directions ('up', 'down', 'left', 'right') by a given amount. Both synchronous and asynchronous versions are available. ```python from cdp_patches.input import SyncInput sync_input = SyncInput(browser=browser) # Scroll down 10 units sync_input.scroll("down", 10) # Scroll up 5 units sync_input.scroll("up", 5) # Scroll right (horizontal) sync_input.scroll("right", 3) # Scroll left (horizontal) sync_input.scroll("left", 3) # Async version await async_input.scroll("down", 10) ``` -------------------------------- ### Scroll Page with Async Input Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/async-usage.md Scrolls the page in the specified direction by the given amount. Supports 'up', 'down', 'left', and 'right' directions. Requires an integer amount for scrolling. ```python await async_input.scroll(direction: Literal["up", "down", "left", "right"], amount: int) ``` -------------------------------- ### Asynchronous Playwright Click with cdp_patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/playwright-usage.md Illustrates asynchronous interaction with Playwright using `async_playwright`. It employs `cdp_patches.input.AsyncInput` to execute a click at coordinates obtained from an asynchronous bounding box calculation for a Playwright Locator. This requires `asyncio`, `playwright`, and `cdp_patches`. ```python import asyncio from playwright.async_api import async_playwright, Locator from cdp_patches.input import AsyncInput # Locator Position Helper async def get_locator_pos(locator: Locator): bounding_box = await locator.bounding_box() assert bounding_box x, y, width, height = bounding_box.get("x"), bounding_box.get("y"), bounding_box.get("width"), bounding_box.get("height") assert x and y and width and height x, y = x + width // 2, y + height // 2 return x, y async def main(): async with async_playwright() as playwright: browser = await playwright.chromium.launch() page = await browser.new_page() async_input = await AsyncInput(browser=browser) # Also works with Contexts # Example: Click Button # Find Button Coords locator = page.locator("button") x, y = await get_locator_pos(locator) # Click Coords => Click Button await async_input.click("left", x, y) asyncio.run(main()) ``` -------------------------------- ### JavaScript Keyboard Event Logging Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/input/keyboard.html This JavaScript code sets up event listeners for 'keydown', 'keypress', and 'keyup' events on a textarea element. It logs event details like key, code, and modifier status to the console and accumulates them in a result string. The `modifiers` function formats modifier key information, and `log` appends event details to the `result`. `getResult` retrieves the accumulated log. ```javascript let textarea = document.querySelector('textarea'); textarea.focus(); textarea.addEventListener('keydown', event => { log('Keydown:', event.key, event.code, event.which, modifiers(event)); }); textarea.addEventListener('keypress', event => { log('Keypress:', event.key, event.code, event.which, event.charCode, modifiers(event)); }); textarea.addEventListener('keyup', event => { log('Keyup:', event.key, event.code, event.which, modifiers(event)); }); function modifiers(event) { let m = []; if (event.altKey) m.push('Alt'); if (event.ctrlKey) m.push('Control'); if (event.shiftKey) m.push('Shift'); return '[' + m.join(' ') + ']'; } let result = ""; function log(...args) { console.log.apply(console, args); result += args.join(' ') + '\n'; } function getResult() { let temp = result.trim(); result = ""; return temp; } ``` -------------------------------- ### Create Scrollable Buttons with Event Handlers (JavaScript) Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/input/scrollable.html This JavaScript code dynamically creates 100 buttons and appends them to the document body. Each button has an 'onclick' event to update its text and an 'oncontextmenu' event to display 'context menu' and prevent the default browser context menu. No external dependencies are required. ```javascript for (let i = 0; i < 100; i++) { let button = document.createElement('button'); button.textContent = i + ': not clicked'; button.id = 'button-' + i; button.onclick = () => button.textContent = 'clicked'; button.oncontextmenu = event => { event.preventDefault(); button.textContent = 'context menu'; } document.body.appendChild(button); document.body.appendChild(document.createElement('br')); } ``` -------------------------------- ### Capture Button Click Event Properties in JavaScript Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/input/button.html This snippet sets up an event listener for a 'button' element. Upon a click, it records properties of the MouseEvent object, including offsets, page coordinates, keyboard state, and event propagation details. It initializes variables to default values before the event listener is attached. ```javascript window.result = 'Was not clicked'; window.offsetX = undefined; window.offsetY = undefined; window.pageX = undefined; window.pageY = undefined; window.shiftKey = undefined; window.pageX = undefined; window.pageY = undefined; window.bubbles = undefined; document.querySelector('button').addEventListener('click', e => { result = 'Clicked'; offsetX = e.offsetX; offsetY = e.offsetY; pageX = e.pageX; pageY = e.pageY; shiftKey = e.shiftKey; bubbles = e.bubbles; cancelable = e.cancelable; composed = e.composed; }, false); ``` -------------------------------- ### Synchronous Playwright Click with cdp_patches Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/playwright-usage.md Demonstrates synchronous interaction with Playwright. It utilizes `cdp_patches.input.SyncInput` to perform a click action at calculated coordinates derived from a Playwright Locator. This requires the `playwright` and `cdp_patches` libraries. ```python from playwright.sync_api import sync_playwright, Locator from cdp_patches.input import SyncInput # Locator Position Helper def get_locator_pos(locator: Locator): bounding_box = locator.bounding_box() assert bounding_box x, y, width, height = bounding_box.get("x"), bounding_box.get("y"), bounding_box.get("width"), bounding_box.get("height") assert x and y and width and height x, y = x + width // 2, y + height // 2 return x, y with sync_playwright() as playwright: browser = playwright.chromium.launch() page = browser.new_page() sync_input = SyncInput(browser=browser) # Also works with Contexts # Example: Click Button # Find Button Coords locator = page.locator("button") x, y = get_locator_pos(locator) # Click Coords => Click Button sync_input.click("left", x, y) ``` -------------------------------- ### CSS Button and Container Styling Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/offscreenbuttons.html Defines the base styles for buttons, including absolute positioning, fixed dimensions, and zero margins. It also sets up the body and html elements for full-width and height relative positioning, and a general div for absolute positioning within its parent. ```css button { position: absolute; width: 100px; height: 20px; margin: 0; } body, html { margin: 0; padding: 0; height: 100%; width: 100%; position: relative; } div { position: absolute; left: 0; top: 0; right: 0; bottom: 0; } ``` -------------------------------- ### Type Text with Async Input Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/async-usage.md Types the given text into an input field. Optionally, the 'fill' parameter can be set to True to simulate pasting. A 'timeout' object must be provided for the operation. ```python await async_input.type(text: str, fill: Optional[bool] = False, timeout: Timeout) ``` -------------------------------- ### Detect Bot Behavior with Input Coordinates (JavaScript) Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/docs/gitbook/input/README.md This snippet checks if page coordinates match screen coordinates, a condition that typically indicates bot-like behavior unless the browser is in full-screen mode. It helps identify potential bypasses for CDP Input domain leaks. Dependencies include the event object `e` with `pageY`, `screenY`, `pageX`, `screenX` properties, and `outerHeight`, `innerHeight` for fullscreen detection. ```javascript var is_bot = (e.pageY == e.screenY && e.pageX == e.screenX) if (is_bot && 1 >= outerHeight - innerHeight){ // fullscreen is_bot = false } ``` -------------------------------- ### JavaScript Button Click Event Listener Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/offscreenbuttons.html Adds a click event listener to all button elements on the page once the DOM is fully loaded. When a button is clicked, it logs a message to the console indicating which button was clicked based on its text content. ```javascript window.addEventListener('DOMContentLoaded', () => { for (const button of Array.from(document.querySelectorAll('button'))) { button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false); } }, false); ``` -------------------------------- ### Capture Input Field Value using JavaScript Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/input/textarea.html This snippet captures the current value of an input field whenever the user inputs text. It utilizes an event listener for the 'input' event. The captured value is then assigned to the global `window.result` variable. This functionality does not depend on any external libraries. ```javascript let input = document.querySelector('input'); input.addEventListener('input', () => result = input.value, false); ``` -------------------------------- ### Capture Textarea Input Value using JavaScript Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/input/textarea.html This snippet captures the current value of a textarea element whenever the user inputs text. It uses an event listener attached to the 'input' event. The captured value is stored in the global `window.result` variable. No external libraries are required. ```javascript window.result = ''; let textarea = document.querySelector('textarea'); textarea.addEventListener('input', () => result = textarea.value, false); ``` -------------------------------- ### CSS Specific Button Offsets Source: https://github.com/kaliiiiiiiiii-vinyzu/cdp-patches/blob/main/tests/assets/offscreenbuttons.html Applies specific absolute positioning offsets to individual buttons identified by their IDs. Each button is offset from the top and right edges of its containing element. ```css #btn0 { right: 0px; top: 0; } #btn1 { right: -10px; top: 25px; } #btn2 { right: -20px; top: 50px; } #btn3 { right: -30px; top: 75px; } #btn4 { right: -40px; top: 100px; } #btn5 { right: -50px; top: 125px; } #btn6 { right: -60px; top: 150px; } #btn7 { right: -70px; top: 175px; } #btn8 { right: -80px; top: 200px; } #btn9 { right: -90px; top: 225px; } #btn10 { right: -100px; top: 250px; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.