How to perform form submissions in Puppeteer?

Performing form submissions in Puppeteer, a headless browser Node.js library, involves a number of steps. Here's a basic guide on how to do it.

Steps to perform form submission in Puppeteer

Step 1: Launch Puppeteer

First, you need to launch Puppeteer and go to the website with the form you want to fill out.

const puppeteer = require('puppeteer');

async function run() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://example.com');

Step 2: Identify form elements

Next, you need to identify the elements of the form you want to fill out. You can do this by inspecting the webpage and identifying the selectors for each field.

For instance, if the form has a text box for a name and a submit button like this:

<form>
  <input id="name" type="text">
  <button id="submit" type="submit">Submit</button>
</form>

Step 3: Fill out the form

You can fill out the form using the page.type method, which types text into a specified selector:

await page.type('#name', 'John Doe');

Step 4: Submit the form

Finally, you can submit the form by clicking the submit button using the page.click method:

await page.click('#submit');

Step 5: Close the browser

You should close the browser after the operation:

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

Complete Code

Here's the complete code that launches Puppeteer, navigates to a webpage, fills out a form, submits it, and then closes the browser:

const puppeteer = require('puppeteer');

async function run() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

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

  // Fill out the form
  await page.type('#name', 'John Doe');

  // Submit the form
  await page.click('#submit');

  await browser.close();
}

run();

Please replace the http://example.com with your actual URL and adjust the selectors (#name, #submit) according to your form structure. Remember that this is a basic example, form submission can be more complex depending on the structure and behavior of the form.

Related Questions

Get Started Now

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