Puppeteer 简明教程

Puppeteer - Non Headless Execution

默认情况下,Puppeteer 在无头 Chromium 中执行测试。这意味着如果我们使用 Puppeteer 运行测试,则我们无法在浏览器中查看执行。

By default, Puppeteer executes the test in headless Chromium. This means if we are running a test using Puppeteer, then we won’t be able to view the execution in the browser.

要启用在有头模式下的执行,我们必须在代码中添加参数:headless:false。

To enable execution in the headed mode, we have to add the parameter: headless:false in the code.

首先,按照 Puppeteer 的基本测试章节中的步骤 1 到 2 操作,如下所示:

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer, which are as follows −

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 - 将以下代码添加到新创建的 testcase1.js 文件中。

Step 3 − Add the below code within the testcase1.js file created.

//adding Puppeteer library
const pt = require('puppeteer');
//adding headless flag to false
pt.launch({headless:false}).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/about/about_careers.htm');
})

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

Step 4 − Execute the code with the command given below −

node <filename>

因此,在我们的示例中,我们将运行下面提到的命令 −

So in our example, we shall run the below mentioned command −

node testcase1.js
about careers

在成功执行命令后,我们将看到执行在带有标题模式中被触发。

After the command has been successfully executed, we shall see the execution getting triggered in a headed mode.