How to Take Screenshots in Puppeteer?

Taking a screenshot with Puppeteer is straightforward. You just need to set the browser’s viewport and use the page.screenshot() method. Here’s how to capture a screenshot of Bright Data’s home page:

      const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Set the viewport dimensions
  await page.setViewport({ width: 1920, height: 1080 });

  // Navigate to Bright Data's home page
  await page.goto('https://brightdata.com');

  try {
    // Capture and save the screenshot
    await page.screenshot({ path: 'brightdata_homepage.jpg' });
  } catch (err) {
    console.error(`Error capturing screenshot: ${err.message}`);
  } finally {
    await browser.close();
    console.log('Screenshot captured successfully');
  }
})();

    

Steps to Take a Screenshot in Puppeteer:

  1. Install Puppeteer: Ensure you have Puppeteer installed in your project.npm install puppeteer
  2. Launch Browser: Start a new browser instance with puppeteer.launch().
  3. Open a New Page: Use browser.newPage() to open a new page.
  4. Set Viewport: Set the viewport dimensions using page.setViewport({ width, height }).
  5. Navigate to URL: Navigate to the desired URL using page.goto('your-website-url').
  6. Capture Screenshot: Use page.screenshot({ path: 'your-file-name.jpg' }) to capture and save the screenshot.
  7. Handle Errors: Wrap the screenshot logic in a try-catch block to handle any errors.
  8. Close Browser: Close the browser instance with browser.close().

This method ensures a quick and reliable way to capture screenshots of web pages using Puppeteer. For more advanced needs, Bright Data’s Puppeteer web scraping browser automatically bypasses website blockades, handling CAPTCHA solving and browser fingerprinting. Scale up with ease using a single API and Bright Data’s robust network, saving you the cost of building your own infrastructure.

Максимальный контроль и эффективность

Добро пожаловать в Scraping Cloud

Ready to get started?