How to handle keyboard actions in Playwright?

Playwright offers several methods to simulate keyboard input, such as typing text, pressing keys, or holding keys down. In this article, we will discuss two key methods: page.type() and page.press().

page.type()

This method allows you to simulate typing text into an input field. It accepts two arguments: a selector for the input field and the text you want to type.

Here's a Python example:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('https://example.com')
    page.type('#input_field_id', 'Hello, World!')
    browser.close()

Here's a JavaScript example:

const playwright = require('playwright');

(async () => {
    const browser = await playwright.chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('https://example.com');
    await page.type('#input_field_id', 'Hello, World!');
    await browser.close();
})();

page.press()

This method allows you to simulate pressing a key on the keyboard. It accepts two arguments: a selector for the input field and the key you want to press.

Here's a Python example:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('https://example.com')
    page.click('#input_field_id') # focus the input field
    page.press('#input_field_id', 'Enter') # Press 'Enter'
    browser.close()

Here's a JavaScript example:

const playwright = require('playwright');

(async () => {
    const browser = await playwright.chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.goto('https://example.com');
    await page.click('#input_field_id'); // focus the input field
    await page.press('#input_field_id', 'Enter'); // Press 'Enter'
    await browser.close();
})();

In these examples, replace #input_field_id with the actual selector of your input field and 'Hello, World!' with the actual text you want to type.

You can also simulate other keyboard actions, like holding a key down, releasing a key, and more, using other methods provided by Playwright. For more details, refer to the official Playwright documentation.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon