ArticleZip > Puppeteer Wait For All Images To Load Then Take Screenshot

Puppeteer Wait For All Images To Load Then Take Screenshot

When using Puppeteer for web scraping or automated testing, capturing a screenshot of a fully loaded webpage can be crucial for visual validation. However, sometimes elements like images may load asynchronously, leading to incomplete screenshots. In this guide, we'll walk you through how to make Puppeteer wait for all images to load before taking a screenshot.

To ensure that all images are fully loaded before capturing the screenshot, we can leverage Puppeteer's `waitForSelector` function in combination with specific image selectors. By waiting for a specific image to be fully loaded, we can be confident that all images on the page have also been loaded.

Here's a step-by-step approach to achieve this:

1. **Identify the Image Selectors:** Before taking the screenshot, identify the image selectors on the webpage that you want to ensure are fully loaded. You can use developer tools in your browser to inspect the elements and get the CSS selectors of the images.

2. **Implement the waitForImagesToLoad Function:** Create a function called `waitForImagesToLoad` that takes the image selectors array and waits for all images specified by the selectors to be loaded. Here's a sample implementation:

Javascript

const waitForImagesToLoad = async (page, imageSelectors) => {
  await Promise.all(
    imageSelectors.map(selector =>
      page.waitForSelector(selector, { visible: true })
    )
  );
};

3. **Integrate waitForImagesToLoad Before Taking the Screenshot:** Incorporate the `waitForImagesToLoad` function into your Puppeteer script before capturing the screenshot. This ensures that the script waits for all specified images to load.

4. **Take the Screenshot:** Once all images are loaded, proceed to capture the screenshot using Puppeteer's `screenshot` function. Here's an example snippet:

Javascript

await waitForImagesToLoad(page, ['img']); // Wait for all img tags to load
await page.screenshot({ path: 'screenshot.png' }); // Take the screenshot

By following these steps, you can make Puppeteer wait for all images to load before capturing a screenshot, ensuring that the screenshot accurately reflects the fully loaded state of the webpage. This approach can be beneficial for various use cases, such as visual testing, monitoring web performance, or creating documentation.

In conclusion, incorporating image loading validation into your Puppeteer scripts can enhance the reliability and accuracy of your automated tasks. With the ability to wait for all images to load before taking a screenshot, you can have more confidence in the results generated by your Puppeteer scripts.

×