Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer: How to submit a form?

Using puppeteer, how could you programmatically submit a form? So far I've been able to do this using page.click('.input[type="submit"]') if the form actually includes a submit input. But for forms that don't include a submit input, focusing on the form text input element and using page.press('Enter') doesn't seem to actually cause the form to submit:

const puppeteer = require('puppeteer');  (async() => {      const browser = await puppeteer.launch();     const page = await browser.newPage();     await page.goto('https://stackoverflow.com/', {waitUntil: 'load'});     console.log(page.url());      // Type our query into the search bar     await page.focus('.js-search-field');     await page.type('puppeteer');      // Submit form     await page.press('Enter');      // Wait for search results page to load     await page.waitForNavigation({waitUntil: 'load'});       console.log('FOUND!', page.url());      // Extract the results from the page     const links = await page.evaluate(() => {       const anchors = Array.from(document.querySelectorAll('.result-link a'));       return anchors.map(anchor => anchor.textContent);     });     console.log(links.join('\n'));     browser.close();  })(); 
like image 976
docta_faustus Avatar asked Aug 20 '17 03:08

docta_faustus


People also ask

How do I submit a form using puppeteer?

Submitting a form with attachments async function uploadFile() { const browser = await puppeteer. launch({ headless: false }); const page = await browser. newPage(); await page. goto('https://www.w3schools.com/howto/howto_html_file_upload_button.asp'); const element = await page.

Can I use puppeteer in browser?

To use Puppeteer with a different version of Chrome or Chromium, pass in the executable's path when creating a Browser instance: const browser = await puppeteer. launch({executablePath: '/path/to/Chrome'}); You can also use Puppeteer with Firefox Nightly (experimental support).

How does a puppeteer work?

Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol. It can also be configured to use full (non-headless) Chrome or Chromium.


2 Answers

If you are attempting to fill out and submit a login form, you can use the following:

await page.goto('https://www.example.com/login');  await page.type('#username', 'username'); await page.type('#password', 'password');  await page.click('#submit');  await page.waitForNavigation();  console.log('New Page URL:', page.url()); 
like image 170
Grant Miller Avatar answered Sep 29 '22 08:09

Grant Miller


Try this

const form = await page.$('form-selector'); await form.evaluate(form => form.submit()); 

For v0.11.0 and laters:

await page.$eval('form-selector', form => form.submit()); 
like image 45
Nam Mai Anh Avatar answered Sep 29 '22 06:09

Nam Mai Anh