Sure! Here’s an example of how you can use Puppeteer to loop through elements on a webpage and display the results in an HTML div:
“`html
“`
In this example, we first import Puppeteer and then define a function called `loopThroughElements()` which uses Puppeteer to interact with a webpage. Inside this function, we launch a new Puppeteer browser, create a new page, and navigate to the desired webpage.
We then use `page.$$()` function to get all elements on the page that match a specific selector. In this example, we’re selecting elements with the attribute `[data-example]`, but you can replace it with any valid CSS selector according to your requirement.
Next, we loop through each element using a JavaScript `for…of` loop, and for each element, we extract its text content using `element.evaluate()` function.
After that, we create a new result div element using `document.createElement(‘div’)` and append it to the existing results div in the HTML using `document.getElementById(‘results’).appendChild(resultDiv)`. The `result` class is added to each result div to apply some styling.
Finally, we close the Puppeteer browser using `browser.close()`.
You can customize this example based on your specific use case by modifying the CSS selector, adding additional processing logic inside the loop, or performing other actions on the webpage with Puppeteer.