To create a custom function in Puppeteer, you can define the function in a separate file and then import it into your Puppeteer script. Here's an example of how you can create a custom function to click on an element with a specific selector:
customFunctions.js
, and define your custom function:const clickElement = async (page, selector) => {
try {
await page.waitForSelector(selector);
await page.click(selector);
} catch (error) {
console.error(`Error clicking element with selector "${selector}": ${error}`);
}
}
module.exports = { clickElement };
const puppeteer = require('puppeteer');
const { clickElement } = require('./customFunctions');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await clickElement(page, 'button#submit');
await browser.close();
})();
In this example, the custom function clickElement
is defined in the customFunctions.js
file and then imported into the main Puppeteer script. The function takes two arguments: the Puppeteer page object and the selector of the element to click. This allows you to easily reuse the function in multiple places in your Puppeteer scripts.