I’m trying to figure out how to submit a form using puppeteer
programmatically. I’ve managed to activate the submission using page.click(‘.submit-button’)
for forms that include a submit button. However, for forms lacking a submit button, using page.press(‘Return’)
after focusing on the text input does not trigger the form submission. How can I handle this scenario effectively?
Example Code:
const puppeteerLib = require('puppeteer');
(async () => {
const browserInstance = await puppeteerLib.launch();
const newPage = await browserInstance.newPage();
await newPage.goto('https://example.com/', {waitUntil: 'networkidle2'});
// Focus on the search input and type the query
await newPage.focus('.search-box');
await newPage.type('example query');
// Try to submit the form
await newPage.press('Return');
// Wait for navigation to complete
await newPage.waitForNavigation({waitUntil: 'domcontentloaded'});
console.log('Page URL:', newPage.url());
// Retrieve result links from the page
const resultLinks = await newPage.evaluate(() => {
const links = Array.from(document.querySelectorAll('.result-item a'));
return links.map(link => link.innerText);
});
console.log(resultLinks.join('\n'));
await browserInstance.close();
})();