Screenshot of a web page using Puppeteer with a specific selector, 웹페이지 스크린샷

To get a screenshot of a web page using Puppeteer with a specific selector, you can follow these steps:

  1. Install Puppeteer by running the command npm install puppeteer in your project directory.

  2. Require Puppeteer in your Node.js script:

const puppeteer = require('puppeteer');
  1. Launch a new browser instance:
const browser = await puppeteer.launch();
  1. Create a new page in the browser:
const page = await browser.newPage();
  1. Navigate to the desired URL:
await page.goto('https://example.com');
  1. Wait for the desired selector to appear:
await page.waitForSelector('#your-selector');
  1. Get the bounding box of the element matching the selector:
const element = await page.$('#your-selector');
const box = await element.boundingBox();
  1. Take a screenshot of the element:
await page.screenshot({
  path: 'screenshot.png',
  clip: {
    x: box.x,
    y: box.y,
    width: box.width,
    height: box.height,
  },
});
  1. Close the browser instance:
await browser.close();

Here's the complete code:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.waitForSelector('#your-selector');
  const element = await page.$('#your-selector');
  const box = await element.boundingBox();
  await page.screenshot({
    path: 'screenshot.png',
    clip: {
      x: box.x,
      y: box.y,
      width: box.width,
      height: box.height,
    },
  });
  await browser.close();
})();

This code will save a screenshot of the element matched by the selector as a PNG image file named screenshot.png in the current directory. You can modify the selector and the path/filename to your liking.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

How to catch exceptions on Future in Java, 자바 Future 에러 잡기

Tomcat(톰캣) SSL 포트 설정

Create reusable templates for page routes in Next.js

fs (File System) module in Node.js

KNN(K-Nearest Neighbors) 활용한 이미지 분류

Reactjs datetime range picker

Read a file in Java, 자바 파일 읽기

[Ubuntu] update-alternatives(Symbolic Link 관리)

In HBase, the "memory to disk" flush operation