How do I automate form submissions using Playwright?

Playwright is a popular tool for automating browser actions, including form submissions. It's available for Python, JavaScript, and other languages.

Python

To automate form submissions in Python, you first need to install the Playwright library. You can do that via pip:

pip install playwright

After that, you need to run the following command to download the necessary browser binaries:

playwright install

Now you can use Playwright to automate the form submission process. Here's an example in Python:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.launch()
    page = browser.new_page()

    page.goto('http://website.com/form')

    # Fill the form
    page.fill('input[name="username"]', 'myUser')
    page.fill('input[name="password"]', 'myPassword')

    # Submit the form
    page.click('button[type="submit"]')

    # Wait for navigation to complete
    page.wait_for_load_state('load')

    browser.close()

with sync_playwright() as p:
    run(p)

JavaScript

To use Playwright in JavaScript, you should have Node.js installed. You can install Playwright using npm:

npm i playwright

Below is an example of how to use Playwright to automate form submissions in JavaScript:

const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  await page.goto('http://website.com/form');

  // Fill the form
  await page.fill('input[name="username"]', 'myUser');
  await page.fill('input[name="password"]', 'myPassword');

  // Submit the form
  await page.click('button[type="submit"]');

  // Wait for navigation to complete
  await page.waitForLoadState('load');

  await browser.close();
})();

Remember to replace 'http://website.com/form', 'myUser', 'myPassword', and the selectors to match your actual form. If there's a CAPTCHA or other anti-bot measures, they may prevent the script from working.

Please know that automating form submissions can cause issues for the website owners and may be against their terms of service, so always use this responsibly.

Related Questions

Get Started Now

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