📷 如何在 Node.js 中使用 JavaScript 截取网页屏幕截图(使用 puppeteer)

2025-05-24

📷 如何在 Node.js 中使用 JavaScript 截取网页屏幕截图(使用 puppeteer)

自动截取网页截图曾经非常困难,但现在使用起来puppeteer却非常简单。Puppeteer 是一个无头的 Chrome Node.js API。因此,您可以用它以编程方式完成所有在 Chrome 浏览器中手动操作的功能。

因此,让我们在codesnacks上创建我的博客的屏幕截图。

首先,我们当然要安装 puppeteer。运行

npm i puppeteer
Enter fullscreen mode Exit fullscreen mode

安装 puppeteer。

const puppeteer = require("puppeteer");

// we're using async/await - so we need an async function, that we can run
const run = async () => {
  // open the browser and prepare a page
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  // set the size of the viewport, so our screenshot will have the desired size
  await page.setViewport({
      width: 1280,
      height: 800
  })

  await page.goto('https://codesnacks.net/')
  await page.screenshot({
      path: 'codesnacks.png',
      fullPage: true
  })

  // close the browser 
  await browser.close();
};

// run the async function
run();
Enter fullscreen mode Exit fullscreen mode

Codesnacks 截图

该代码片段将创建整个页面的屏幕截图,宽度为 1280 像素。当然,您也可以设置其他尺寸。屏幕截图将保存在脚本所在的目录中。您可以在 .js 文件中更改文件的目录和名称path

这是一种非常简单的截图方法。如果你对 Puppeteer 的其他功能感兴趣,并且不想错过我即将发布的本系列文章,请考虑关注我。

文章来源:https://dev.to/benjaminmock/how-to-take-a-screenshot-of-a-page-with-javascript-1e7c
PREV
VS Code 扩展助您成为更高效的开发人员🤓🤓🤓 Surround
NEXT
程序员的新黄金法则