I’m trying to use Puppeteer to fill out forms on a webpage. Right now, I’m using page.type() to input text into fields. The problem is that when I use a selector that matches multiple elements, it only fills the first one it finds.
What I want to do is fill all the input fields that match a specific selector. For example, I want to put the same text in every input that has the class ‘red’.
Here’s what I’ve tried:
await page.type('input.red', 'some text');
But this only fills the first input with the ‘red’ class. How can I make it fill all of them? Is there a way to loop through all matching elements or use a different Puppeteer method to achieve this?
I’ve dealt with this exact problem before, and I found a neat solution using page.evaluate(). It’s super flexible and lets you manipulate multiple elements at once. Here’s what worked for me:
This code targets all inputs with the ‘red’ class and sets their values in one go. It’s fast and efficient, especially when you’re dealing with a lot of fields.
One tip: make sure your page is fully loaded before running this. I’ve had issues with timing before, so I usually add a short delay or wait for a specific element to appear first.
Also, if you need to actually simulate typing (like for triggering certain events), you might want to look into using page.$$ to get all the elements and then loop through them with elementHandle.type(). It’s a bit slower but can be necessary in some cases.
I’ve found that using page.evaluate() can be quite effective for this scenario. It allows you to execute JavaScript directly in the browser context, giving you more flexibility. Here’s an approach I’ve used successfully:
This method selects all inputs with the ‘red’ class and sets their values in one go. It’s efficient and works well for multiple elements. Just make sure your page is fully loaded before running this to avoid any timing issues.