Puppeteer 简明教程

Puppeteer - Device Emulation

我们可以在 Puppeteer 中使用移动设备配置运行测试并检查网页的响应特性。Puppeteer 支持的设备列表可从 Chrome DevTools 中获得。右击在 Chrome 浏览器中打开的页面,然后选择“检查”。

We can run tests with mobile configurations in Puppeteer and check the responsive property of a webpage. The list of devices that the Puppeteer supports can be obtained from the Chrome DevTools. Right-click on a page opened in the Chrome browser, then select Inspect.

select inspect

然后,单击切换设备工具栏。

Then, click on the Toggle Device Toolbar.

toggle device toolbar

单击弹出的菜单 - 响应可获取设备列表。

Click on the dropdown - Responsive to get the list of devices.

responsive

要模拟某个设备,我们必须使用 emulate() 方法,并将要模拟的设备作为该方法的参数传入。此方法的语法如下所示−

To emulate a device, we have to use the method emulate() and the device to be emulated is passed as a parameter to this method. The syntax for this method is as follows −

const m = puppeteer.devices['iPhone X']
//emulate iPhoneX
await page.emulate(m)

让我们使用 Puppeteer 中的 emulate 函数模拟 iPhone X 设备。

Let us emulate the device iPhone X using the emulate function in 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.

//Puppeteer library
const puppeteer = require('puppeteer')
//launch browser in headed mode
puppeteer.launch({headless:false}).then(async browser => {
   //browser new page
   const page = await browser.newPage()
   //set device to iPhone X
   const m = puppeteer.devices['iPhone X']
   //emulate iPhoneX
   await page.emulate(m)
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //capture screenshot of emulated device
   await page.screenshot({ path: 'iPhoneDevice.png'})
   //browser close
   await browser.close()
})

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

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

node <filename>

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

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

node testcase1.js
iphone device

在命令成功执行后,在页面目录中将创建一个名为 iPhoneDevice.png 的新文件。其中包含适用于 iPhone X 设备的模拟网页的屏幕截图。

After the command has been successfully executed, a new file called the iPhoneDevice.png gets created within the page directory. It contains the captured screenshot of the emulated webpage for the iPhone X device.