Puppeteer 简明教程

Puppeteer - Basic Test

要开始对 Puppeteer 进行基本测试,我们必须执行以下提到的步骤:

To start with a basic test on Puppeteer, we have to follow the below mentioned steps −

Step 1 - 在创建 node_modules 文件夹的目录中创建一个新文件(人偶和人偶核已安装的位置)。

Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).

人偶安装的详情在人偶安装篇章中进行了讨论。

The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.

右击创建 node_modules 文件夹的文件夹,然后点击新建文件按钮。

Right-click on the folder where the node_modules folder is created, then click on the New file button.

node modules

Step 2 - 输入文件名,如 testcase1.js。

Step 2 − Enter a filename, say testcase1.js.

testcase1 js

Step 3 - 在该文件中添加以下代码 −

Step 3 − Add the below code in this file −

//adding Puppeteer library
const pt = require('puppeteer');
pt.launch().then(async browser => {
   //browser new page
   const p = await browser.newPage();
   //set viewpoint of browser page
   await p.setViewport({ width: 1000, height: 500 })
   //launch URL
   await p.goto('https://www.tutorialspoint.com/index.htm')
   //capture screenshot
   await p.screenshot({
      path: 'tutorialspoint.png'
   });
   //browser close
   await browser.close()
})

Step 4 - 使用以下命令执行代码:

Step 4 − Execute the code with the following command −

node <filename>

因此,在我们的示例中,我们将运行以下命令 -

So in our example, we shall run the following command −

node testcase1.js
browser in headless mode

在成功执行命令后,将在页面目录中创建一个称为 tutorialspoint.png 的新文件。其中包含在无头模式下在浏览器中启动的页面的捕获的屏幕截图。

After the command has been successfully executed, a new file called the tutorialspoint.png gets created within the page directory. It contains the captured screenshot of the page launched in the browser in a headless mode.