Puppeteer 简明教程

Puppeteer - Quick Guide

Puppeteer - Introduction

Puppeteer 用于自动化和简化前端开发和测试。它由 Google 推出。Puppeteer 基于 Node.js 库,并且是开源的。

Puppeteer is used for automation and streamlining of the frontend development and testing respectively. It was introduced by Google. Puppeteer is based on the Node.js library and is open-source.

Puppeteer 包含用于以无头模式或 Chromium(遵循 DevTools 中的协议)交互和管理 Chrome 浏览器的 API。但是,它还可用于在 Chrome/Chromium/Edge/Firefox 等浏览器上执行非无头操作。

Puppeteer contains APIs to interact and manage Chrome browser in headless mode or Chromium (following the protocols in DevTools). However, it can also be used for non-headless execution on browsers like Chrome/Chromium/Edge/Firefox.

Puppeteer 可用于自动执行大部分 UI 测试、键盘、鼠标移动等操作。它可用于测试使用 Angular 和 Angularjs 开发的应用程序。使用 Puppeteer 可以执行网页抓取和抓取等操作。

Puppeteer can be used for the automating majority of UI testing, keyboards, mouse movements, and so on. It can be used to test applications developed in Angular and Angularjs. The actions like web page crawling and scraping can be performed with Puppeteer.

Puppeteer 不被视为 Selenium、Cypress、Protractor 等自动化工具。它主要用于管理 Chromium 浏览器的内部功能。我们可以通过按 F12 或 Command+Option+C(在 MacOS 中)在 Chrome 浏览器中打开 DevTools。

Puppeteer is not considered as an automation tool like Selenium, Cypress, Protractor, and so on. It is mostly used to manage the internal features of the Chromium browser. We can open DevTools in the Chrome browser, by pressing F12 or Command+Option+C(in MacOS).

automation and streamlining

Puppeteer 类似于开发工具,因为它能够执行开发人员执行的大部分任务,如处理请求和响应、查找元素、网络流量和性能等等。

Puppeteer is like a development tool as it is capable of performing a majority of tasks performed by a developer like handling requests and responses, locating elements, network traffic and performance, and so on.

如果追溯过去几年 Puppeteer 下载的 npm 趋势,我们将观察到 Puppeteer 使用的增长趋势(可从以下链接获得)−

If we follow the npm trends for Puppeteer download for the last few years, we shall observe an upward trend towards the use of Puppeteer (available from the below link) −

puppeteer downloads

Puppeteer Architecture

Puppeteer 利用 Node 库,该库提供了用于管理 Chromium 或 Chrome 浏览器的顶级 API。这可以通过遵循 DevTools 的协议来完成。

Puppeteer utilises the Node library that gives a top-class API for managing Chromium or Chrome browsers. This is done by following the protocols of DevTools.

Puppeteer 具有以下层级 −

Puppeteer has the below hierarchy −

  1. Browser(with/without headless mode) − The browser performs the actions to be executed on the browser engine.

  2. Chromium Development Project or CDP − The Chromium is the real place where all the operations are executed. The browsers - Microsoft Edge and Chrome utilise Chromium as browser engine.

  3. Puppeteer − This is actually a package based on the node module.

  4. Automation test code − This is also known as the Nodejs level. Here, the actual automation code is developed by the end-user using JavaScript.

Puppeteer - Element Handling

我们可以使用 Puppeteer 处理页面上的元素。一旦我们导航到一个网页,我们就需要与页面上的 web 元素交互,比如点击链接/按钮,在编辑框中输入文本,以此来完成我们的自动化测试用例。

We can handle elements on page with Puppeteer. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的首要任务是识别该元素。为了唯一地获取一个元素的属性,我们需要对其进行检查(右击该元素,然后选择“检查”选项)。ElementHandle 对象由方法创建,分别为:page .、page . $ $和 page . $ x。这些对象引用页面中的元素或标签。

For this, our first job is to identify the element. To get the property of an element uniquely we need to inspect it (right-click on the element then select the option Inspect). The ElementHandle objects are created by the methods - page.$, page.$$ and page.$x. These objects refer to an element or tag in a page.

Puppeteer Methods to Locate Elements

这些方法列在下面:

These methods are listed below −

page.$(locator value)

page.$(locator value)

此方法产生带有 ElementHandle 的 Promise。ElementHandle 是已识别元素的一个对象。如果有多个元素具有相同定位值,则仅从页面的左上角返回第一个匹配的元素。

This method yields a Promise with the ElementHandle. The ElementHandle is an object of the identified element. If there are multiple elements having the same locator value, then only the first matching element from the top left corner of the page shall be returned.

page.$$(locator value)

page.$$(locator value)

此方法产生带有 ElementHandle 数组的 Promise。如果有多个元素具有相同定位值,则以数组形式返回所有匹配元素。

This method yields a Promise with an array of ElementHandle. If there are multiple elements having the same locator value, then all matching elements shall be returned in the form of an array.

page.$x(xpath value)

page.$x(xpath value)

此方法产生带有 ElementHandle 数组的 Promise。如果有多个元素具有相同 xpath 值,则以数组形式返回所有匹配元素。如果有一个匹配的元素,则返回的数组将具有单个元素。

This method yields a Promise with an array of ElementHandle. If there are multiple elements having the same xpath value, then all matching elements shall be returned in the form of an array. In case, there is one matching element, then the array returned shall have a single element.

ElementHandle 方法,如 elementHandle.$、elementHandle.$$ 和 elementHandle.$x 可应用于一个元素。在这种情况下,应该在当前 ElementHandle 的 DOM 中搜索一个元素,而不在整个 DOM 中。

The ElementHandle methods like elementHandle.$, elementHandle.$$ and elementHandle.$x can be applied to an element. In that case, an element shall be searched within the DOM of the present ElementHandle and not in the entire DOM.

在下图中,让我们举一个带有 li 标签的元素(具有父元素 ul)和 class 属性值 heading 的示例。要在页面上使用 ElementHandle 方法对其进行识别,则表达式应如下所示:

In the below image, let us take the example of an element having the li tag (having a parent element ul) and class attribute value as heading. To identify it using the ElementHandle method on the page, the expression should be as follows −

const n = await page.$(".heading")

要在元素上使用 ElementHandle 方法对其进行识别,则表达式应如下所示:

To identify it using the ElementHandle method on an element, the expression should be as follows −

const m = await page.$("ul")
const p = await m.$(".heading")

现在,参阅下面给出的一个具有 li 标签的元素的图片

Now, refer the image given below of an element having the li tag

element having the li tag

Types of Locators

以下是 Puppeteer 中的定位符类型列表:

The types of locators in Puppeteer are listed below −

  1. ID

  2. Class

  3. Type

  4. Xpath

  5. Attribute

  6. Type

为了使用上述定位符,我们应该对 HTML 代码有基本的了解。我们举一个具有以下特性的编辑框的示例:

To work with the above locators we should have the basic understanding of HTML code. Let us take an example of an edit box having the below mentioned properties −

types of locators

此处,input 是标签名称。HTML 中的标签可能有或没有属性。元素的类型、类、名称、ID 等是元素的属性。

Here, input is the tagname. A tag in HTML may or may not have attributes. The type, class, name, id and so on are the attributes of the element.

例如,在表达式 class = "gsc-input" 中,= 左侧的文本是属性名称 (class),右侧是属性值 (gsc-input)。

For example, in the expression class = "gsc-input", text to the left of = is the attribute name (class) and to the right of = is the attribute value (gsc-input).

属性可能具有或不具有分配的值。此外,如果分配了一个值,那么它应该用双引号或单引号括起来。属性的值由开发人员根据自己的选择设置。

An attribute may or may not have a value assigned. Also, if a value is assigned, then it should be enclosed in double or single quotes. The value of an attribute is set by a developer as per his choice.

Puppeteer - Usage of Google

Puppeteer 的用法列于下方:

Puppeteer usages are listed below −

  1. Puppeteer can be used for scrapping contents from a webpage. The scrapping means pulling out data from a particular website.

  2. Puppeteer can be used to capture screenshots. It can be used to export web pages in the form of a PDF.

  3. Puppeteer does not require an external driver or library. It can be run on the actual browser in a headless mode.

  4. It can be used as a good alternative to other browser automation tools like Selenium or Cypress. Sometimes, puppeteer features are even better than both of them.

  5. It is super-fast in execution and can be used to execute tests in headless and headed modes.

  6. Puppeteer has a very agile community support having more than 60,000 starts in GitHub. Refer the link given herewith: https://github.com/puppeteer/puppeteer

  7. Puppeteer supports headless execution and hence it can be used in platforms like Unix, Linux, Cloud, AWS, and so on.

  8. It can be used to crawl a SPA (Single Page Application) and produce pre-rendered content. The crawling means saving a local static object of a webpage and utilising it offline in the absence of the real webpage obtained from the internet.

  9. It can be used for the automating majority of UI testing, keyboards, mouse movements, form submissions etc.

  10. Puppeteer can be used to construct a recent, automated test environment. It can run tests on the latest version Chrome by utilising the most recent features of JavaScript and browser.

  11. Puppeteer can be used to obtain the timeline trace of a web application to determine its performance. Moreover, it can be used to check the Chrome Extensions and to obtain the coverage of HTML and CSS utilized by a webpage.

Puppeteer - NodeJS Installation

Puppeteer 代码实现是使用 JavaScript 完成的。为此,必须安装 NodeJS,因为它是 JavaScript 引擎。只有在安装后,我们才能执行 Puppeteer 测试。

Puppeteer code implementation is done using JavaScript. For this, NodeJS has to be installed since it is a JavaScript engine. Only after its installation, we can execute Puppeteer tests.

配置 NodeJS 的步骤如下 −

The steps to configure NodeJS are listed below −

Step 1 − 启动具有以下链接的应用程序 −

Step 1 − Launch the application having the below link −

Step 2 − 根据我们使用的本地操作系统(Windows、Mac 或 Linux),单击链接下载安装程序。

Step 2 − As per the local operating system (Windows, Mac or Linux) we are using, click on the link to download the Installer.

installation of nodejs

Step 3 − 安装程序下载完毕后,单击它。我们将导航到 Node.js 安装程序欢迎界面。单击继续。

Step 3 − Once the installer is downloaded, click on it. We shall be navigated to the Node.js Installer welcome screen. Click on Continue.

node js installer

Step 4 − 同意 Nodejs 的协议条款。

Step 4 − Agree to the terms of agreement of Nodejs.

terms of agreement of nodejs

Step 5 - 点击安装。

Step 5 − Click on Install.

Step 6 − 一旦显示 Nodejs 安装成功的消息,单击关闭。

Step 6 − Once the success message of Nodejs installation is displayed, click on Close.

success message of nodejs installation

Step 7 − 要检查 Nodejs 是否成功安装,请打开终端并运行命令:node。

Step 7 − To check if Nodejs is installed successfully, open the terminal and run the command: node.

nodejs is installed successfully

应显示机器中安装的 Nodejs 版本。

The version of the Nodejs installed in the machine should get displayed.

Puppeteer - VS Code Configuration

安装 Visual Studio (VS) Code 的步骤如下−

The steps to install the Visual Studio (VS) Code are listed below −

Step 1 - 导航到以下链接 -

Step 1 − Navigate to the below link −

Step 2 − 根据本地操作系统(例如 macOS、Linux 或 Windows),我们需要选择下载链接。

Step 2 − Depending on the local operating system we have for example - macOS, Linux or Windows, we need to choose the link for download.

local operating system

Step 3 − 单击“下载”按钮后,将下载一个 zip 文件。下载此文件完成后,单击该文件,Visual Studio Code 应用程序应该可供使用。

Step 3 − A zip file gets downloaded after clicking the Download button. After downloading this file has completed, click on it and the Visual Studio Code application should become available for use.

visual studio code

Step 4 − 双击它,Visual Studio Code 应用程序应随欢迎页面一起启动。

Step 4 − Double-click it and the Visual Studio Code application should launch along with the welcome page.

visual studio code application

Puppeteer - Installation

Puppeteer 的安装步骤如下 −

The steps for installation of Puppeteer are listed below −

Step 1 − 安装 NodeJS。

Step 1 − Install NodeJS.

有关如何安装 NodeJs 的详细信息,请在 NodeJS 的安装章节中详细讨论。

The details on how to install NodeJs is discussed in detail in the Chapter of Installation of NodeJS.

Step 2 − 在某个位置创建一个空文件夹,比如 puppeteer。

Step 2 − Create an empty folder, say puppeteer in a location.

Step 3 − 启动 Visual Studio 代码应用程序,单击打开文件夹链接并导入我们在步骤 2 中创建的文件夹。

Step 3 − Launch the Visual Studio Code application and click on the Open folder link and import the folder we have created in Step2.

launch the visual studio

有关如何安装 VS 代码的详细信息,请在 VS 代码配置章节中详细讨论。

The details on how to install VS Code is discussed in detail in the Chapter of VS Code Configuration.

Step 4 − 打开终端,并从当前目录移动到我们在步骤 2 中创建的空文件夹的目录。然后运行以下命令 −

Step 4 − Open the terminal and move from the current directory to the directory of the empty folder that we have created in Step 2. Then run the following command −

npm

Step 5 − 对于 Puppeteer 安装,运行以下命令 −

Step 5 − For Puppeteer installation, run the below mentioned command −

npm install puppeteer

或者,

Or,

npm i puppeteer
puppeteer installation

Step 6 − 对于 Puppeteer core 的安装,运行以下命令 −

Step 6 − For installation of Puppeteer core, run the below mentioned command −

npm i puppeteer-core

Step 7 − 安装 Puppeteer 和 Puppeteer core 后,我们将在我们在步骤 2 中创建的空文件夹中找到 node_modules 文件夹和 package.json 文件。

Step 7 − After the installation of Puppeteer and Puppeteer core, we shall find the node_modules folder and package.json file generated within the empty folder we created in Step 2.

installation of puppeteer

Step 8 − 在测试中,我们必须在代码中添加以下 Puppeteer 库。

Step 8 − While working on a test, we have to add the below Puppeteer library in the code.

const pt = require('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.

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.

Comparison Between Puppeteer & Selenium

Puppeteer 和 Selenium 之间的主要区别如下 -

The major differences between Puppeteer and Selenium are given below −

Sr.No

Puppeteer

Selenium

1

Puppeteer is developed mainly for Chromium so the tests developed are mainly executed in Chrome.

Selenium can be used to execute tests on multiple browsers like Chrome, Firefox, IE, Safari, and so on.

2

Puppeteer code can be implemented only in JavaScript.

Selenium code can be implemented on multiple languages like Java, Python, JavaScript, C#, and so on.

3

Puppeteer provides APIs to manage headless execution in Chrome by using the DevTools protocol.

Selenium requires additional external browser drivers that trigger tests as per the user commands.

4

Puppeteer manages the Chrome browser.

Selenium is primarily used to execute tests to automate the actions performed on the browser.

5

Puppeteer is faster in executing tests than Selenium.

Selenium is slower in executing tests than Puppeteer.

6

Puppeteer is a module in node developed for Chromium engine.

Selenium is a dedicated test automation tool.

7

Puppeteer can be used for API testing by utilising the requests and the responses.

API testing with Selenium is difficult.

8

Puppeteer can be used to verify the count of CSS and JavaScript files utilised for loading a webpage.

Selenium cannot be used to verify the count of CSS and JavaScript files utilised for loading a webpage.

9

Puppeteer can be used to work on the majority of features in the DevTools in the Chrome browser.

Selenium cannot be used to work on the majority of features in the DevTools in the Chrome browser.

10

Puppeteer can be used to execute tests on various devices with the help of the emulators.

Using an emulator with Selenium is not easy.

11

Puppeteer can be used to obtain the time needed for a page to load.

Selenium cannot be used to obtain the time needed for a page to load.

12

Puppeteer can be used to save a screenshot in both image and PDF formats.

Selenium can be used to save a screenshot in both image and PDF formats only in the Selenium 4 version.

13

Puppeteer was first introduced in the year 2017.

Selenium was first introduced in the year 2004.

14

In Puppeteer, we can verify an application without image loading.

In Selenium, we can verify an application without image loading.

Comparison Between Puppeteer & Protractor

Puppeteer 和 Protractor 之间的主要区别如下 -

The major differences between Puppeteer and Protractor are given below −

Sr.No.

Puppeteer

Protractor

1

Puppeteer is a module in node developed for Chromium engine.

Protractor is a dedicated test automation tool.

2

Puppeteer is faster in executing tests than Protractor.

Protractor is slower in executing tests than Puppeteer.

3

Puppeteer is developed mainly for Chromium so the tests developed are mainly executed in Chrome.

Protractor can be used to execute tests on multiple browsers like Chrome, Firefox, IE, Safari, and so on.

4

Puppeteer can be used for API testing by utilising the requests and the responses.

API testing with Protractor is difficult.

5

Puppeteer can be used to verify the count of CSS and JavaScript files utilised for loading a webpage.

Protractor cannot be used to verify the count of CSS and JavaScript files utilised for loading a webpage.

6

Puppeteer can be used to work on the majority of features in the DevTools in the Chrome browser.

Protractor cannot be used to work on the majority of features in the DevTools in the Chrome browser.

7

Puppeteer can be used to execute tests on various devices with the help of the emulators.

Using an emulator with Protractor is not easy.

8

Puppeteer can be used to save a screenshot in both image and PDF formats.

Protractor can be used to save a screenshot in only image format.

9

Puppeteer can be used to obtain the time needed for a page to load.

Protractor cannot be used to obtain the time needed for a page to load.

10

In Puppeteer, we can verify an application without image loading.

In Protractor, we can verify an application without image loading.

让我们观察过去两年中 Puppeteer 和 Protractor 的 npm 趋势。我们应观察到比 Protractor 使用更多 Puppeteer 的上升趋势(可从下面链接中获取)−

Let us observe the npm trends of Puppeteer and Protractor for the last two years. We shall observe an upward trend towards the use of Puppeteer than Protractor (available from the below link) −

protractor vs puppeteer

Comparison Between Puppeteer & Cypress

Puppeteer 和 Cypress 之间的主要区别如下 −

The major differences between Puppeteer and Cypress are as follows −

Sr.No

Puppeteer

Cypress

1

Puppeteer is a module in node developed for Chromium engine.

Cypress is a dedicated test automation framework developed in JavaScript.

2

Puppeteer is mainly used for web page scraping and crawling SPA(Single Page Application).

Cypress is mainly used to automate test cases for a complete application.

3

Assertions in Puppeteer are based on the Mocha, Jasmine or Jest frameworks.

Cypress has its individual assertions.

4

VS Code and Webstorm are mostly used as an IDE for Puppeteer.

Cypress has its individual IDE.

5

Puppeteer is developed mainly for Chromium so the tests developed are mainly executed in Chrome.

Cypress can be used to execute tests on multiple browsers like Chrome, Firefox, Electron and so on.

6

Puppeteer has no dashboard.

Cypress has its dashboard to see the recorded tests and gives us detail on the events that took place during execution.

7

Puppeteer is faster in executing tests than Cypress.

Cypress is slower in executing tests than Puppeteer.

8

Puppeteer APIs are not easier to use than Cypress.

Cypress APIs are easier to use than Puppeteer.

9

Puppeteer comes free of cost.

Cypress has both free and paid versions.

10

Puppeteer has no features of fixtures and group fixtures in tests.

Cypress has the features of fixtures and group fixtures applied in tests.

11

Grouping of tests for execution cannot be done in Puppeteer.

Grouping of tests for execution can be done in Cypress.

12

Puppeteer has no mocking capabilities.

Cypress has the mocking capabilities.

让我们观察一下过去两年的 Puppeteer 和 Cypress 的 npm 趋势。我们观察到 Puppeteer 和 Cypress 的使用趋势都在上升(可通过以下链接获得)−

Let us observe the npm trends of Puppeteer and Cypress for the last two years. We shall observe an upward trend towards the use of both Puppeteer and Cypress (available from the below link) −

cypress vs puppeteer

Puppeteer - Browser Operations

人偶可以通过以下给定方法执行浏览器操作 -

The browser operations can be done by Puppeteer with the help of below given methods −

launch()

它用来打开新的浏览器,并与 Chromium 实例连接。它有一些可选参数,如下所示 -

It is used to open new browsers and connect with an instance of Chromium. It has some optional parameters which are as follows −

Product - 这是字符串类型,用于指向要启动的浏览器。

Product − This is of String type and is used to point to the browser to be launched.

Syntax

其语法如下:

The syntax is as follows −

let l = await puppeteer.launch({product : "chrome" })

headless - 这是布尔类型(默认值为 true),且必须设置为 false 值,才能在图形用户界面模式下执行测试。

headless − This is of Boolean type(default value is true) and it has to be set with false value inorder to execute the tests in headed mode.

Syntax

其语法如下:

The syntax is as follows −

let l = await puppeteer.launch({headless : false})

devtools - 这是布尔类型。如果将其设为 true,则 DevTools 将在每个浏览器标签中自动打开。此外,如果 devtools 设置为 true,则 headless 参数应该设为 false。

devtools − This is of Boolean type. If it is set to true, then DevTools shall open automatically in each browser tab. Also, the headless parameter should be set to false, if devtools is set to true.

Syntax

其语法如下:

The syntax is as follows −

let l = await puppeteer.launch({devtools: true})

defaultViewport - 这是对象类型。它为一个页面提供了持久视区(视区的默认值为 800*600)。我们可以在 width 和 height 中指明像素的整数值来修改视区的大小。

defaultViewport − This is of type object. It provides a persistent viewport for a page(default value of viewport is 800*600). We can modify the size of the viewport by mentioning integer values in width and height for pixels.

Syntax

其语法如下:

The syntax is as follows −

let l = await puppeteer.launch({defaultViewport: { width: 500, height: 459}})

slowMo − 这是一个数字类型。该参数用于放慢 Puppeteer 执行一段时间,以毫秒为单位。

slowMo − This is of type number. This parameter is used to slow down the Puppeteer execution for some time, provided in milliseconds.

Syntax

其语法如下:

The syntax is as follows −

let l = await puppeteer.launch({slowMo: 500})

goTo()

用于导航到网页。要导航到的页面的网址作为参数传递。

It is used to navigate to a webpage. The URL of the page to be navigated is passed as a parameter.

Syntax

其语法如下:

The syntax is as follows −

await page.goto('https://www.tutorialspoint.com/index.htm')

close()

用于关闭打开的浏览器。

It is used to close an opened browser.

Syntax

其语法如下:

The syntax is as follows −

await browser.close()

browserContexts()

这会产生一个数组,其中包含所有已打开的浏览器上下文。

This yields an array of all opened browser contexts.

createIncognitoBrowserContext()

它会在隐身模式下打开一个新浏览器。

It opens a new browser in incognito context.

defaultBrowserContext()

这会产生一个默认浏览器上下文。

It yields a default browser context.

disconnect()

用于断开 Puppeteer 与浏览器实例的连接。

It is used to disconnect Puppeteer from the browser instance.

isConnected()

用于验证浏览器是否已连接。

It is used to verify whether a browser is connected.

newPage()

它会产生一个包含新页面对象的 Promise。

It yields a Promise with a new page object.

pages()

它会产生一个包含所有打开页面对象的数组的 Promise。

It yields a Promise with an array of all open page objects.

process()

如果使用 launch 方法创建实例,它会产生一个浏览器进程。此外,如果使用 connect 方法创建实例,它会产生一个 null 值。

It yields a browser process if the instance is created with the launch method. Furthermore, it yields a null value if the instance is created with the connect method.

target()

它会产生浏览器的目标。

It yields the target for a browser.

targets()

它会产生一个 Promise,其中包含所有处于活动状态的目标的数组。

It yields a Promise containing the array of all targets which are active.

Puppeteer - Handling Tabs

我们可以使用以下方法在 Puppeteer 中处理选项卡 -

We can handle tabs in Puppeteer using the below methods −

newPage()

我们可以使用浏览器对象中提供的此方法打开一个新选项卡。

We can open a new tab using this method available in the browser object.

Syntax

其语法如下:

The syntax is as follows −

const p = await browser.newPage()

close()

我们可以使用此方法关闭已打开的选项卡。

We can close the tab opened using this method.

Syntax

其语法如下:

The syntax is as follows −

await p.close()

close()

我们可以使用浏览器对象中提供的此方法关闭所有已打开的选项卡。

We can close all the tabs opened using this method available in the browser object.

Syntax

其语法如下:

The syntax is as follows −

await browser.close()

首先,按照人偶基本测试章节执行步骤 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')
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 command given below −

node <filename>

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

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

node testcase1.js
tutorialspoint

命令成功执行后,将在页面目录中创建一个名为 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.

Puppeteer - Basic Commands

下面列出了一些 Puppeteer 的基本命令 −

Some of the basic commands of Puppeteer are listed below −

title()

此命令用于获取当前页面的标题。

This command is used to obtain the title of the present page.

Syntax

其语法如下:

The syntax is as follows −

await page.title()

url()

此命令用于获取浏览器中当前启动的应用程序的 URL。

This command is used to obtain the URL of the application currently launched in the browser.

Syntax

其语法如下:

The syntax is as follows −

await page.url()

content()

此命令用于获取页面源代码。

This command is used to obtain the page source code.

Syntax

其语法如下:

The syntax is as follows −

await page.content()

首先,按照人偶基本测试章节执行步骤 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');
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/questions/index.php')
   //obtain page title
   console.log("Page title: " + await p.title())
   //obtain URL
   console.log("Url: " + await p.url())
   //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
terminal

成功执行命令后,页面标题——最佳技术问题和答案被打印在控制台中。此外,URL—— www.tutorialspoint.com/questions/index.php 被打印在控制台中。执行已在无头模式下进行。

After the command has been successfully executed, the page title - The Best Technical Questions and Answers gets printed in the console. Also, the URL - www.tutorialspoint.com/questions/index.php gets printed in the console. The execution has happened in the headless mode.

Puppeteer - Firefox

我们可以在 Firefox 中运行在 Puppeteer 中开发的测试。必须记住,在 Firefox 中执行测试时,Puppeteer 使用其内部 Firefox 浏览器,而不是本地系统中安装的 Firefox 浏览器。

We can run the tests developed in Puppeteer in Firefox. It must be remembered that while executing the test in Firefox, Puppeteer uses its internal Firefox browser and not the Firefox browser installed in the local system.

Step 1 - 我们必须首先通过执行以下命令为 Firefox 浏览器安装 Puppeteer -

Step 1 − We have to first install Puppeteer for the Firefox browser by executing the below command −

npm install puppeteer-firefox
puppeteer firefox

此外,我们必须在代码中添加 Firefox-Puppeteer 库。

Also, we have to add the Firefox-Puppeteer library in the code.

const f = require('puppeteer-firefox')

首先,按照人偶基本测试章节执行步骤 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- Firefox library
const pt = require('puppeteer-firefox');
//adding headless flag to false
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/about/about_careers.htm')
   //get browser
   const v = await p.browser().version();
   console.log("Browser: " + v)
   //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
firefox

成功执行命令后,执行测试的浏览器 - Firefox/65.0 将打印到控制台。

After the command has been successfully executed, the browser in which the test is executed - Firefox/65.0 gets printed in the console.

Puppeteer - Chrome

默认情况下,以无头模式在 Chrome 或 Chromium 浏览器中执行 Puppeteer 中编写的测试。此外,我们必须在代码中添加以下 Puppeteer 库。

The tests written in Puppeteer are executed in the Chrome or Chromium browser in a headless mode by default. Also, we have to add the below Puppeteer library in the code.

const pt = require('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');
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')
   //get browser
   const v = await p.browser().version();
   console.log("Browser: " + v)
   //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
headless chrome

在成功执行命令后,执行测试的浏览器 - HeadlessChrome/92.0.4512.0 将打印在控制台中。

After the command has been successfully executed, the browser in which the test is executed - HeadlessChrome/92.0.4512.0 gets printed in the console.

Puppeteer - Handling Confirm Alerts

Puppeteer 能够处理警报。Selenium、WebdriverIO 等自动化工具会在警报出现在页面上之后接受或关闭它。

Puppeteer is capable of handling Alerts. The automation tools like Selenium, WebdriverIO, and so on, accept or dismiss an alert after it has appeared on the page.

但是,在 Puppeteer 中,用户必须在警报出现在页面上之前给出是否接受或关闭警报的指示。为此,必须使用 Puppeteer 触发 on 事件侦听器。

However in Puppeteer, the user has to give direction whether to accept or dismiss an alert before it appears on the page. For this, the on event listener has to be triggered using Puppeteer.

Methods for Handling Confirm Alerts

以下是处理警报的一些方法 −

Some methods to work with Alerts are listed below −

  1. accept(): Promise<void> − This method is used to accept an alert.

  2. message(): string − This method is used to yield the message obtained in an alert.

  3. type(): DialogType − This method is used to obtain the Dialog type. A Dialog type can be a prompt, confirm or prompt.

  4. dismiss(): Promise<void> − This method is used to dismiss an alert.

在下面给出的图片中,单击点击查看 JS 确认后,将显示一个确认警报。让我们获取警报中的文本。

In the below given image, on clicking Click for JS Confirm, a confirm alert is displayed. Let us obtain the text on the alert.

javascript alerts

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function confirmAlert(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage();
   //on event listener trigger
   page.on('dialog', async dialog => {
      //get alert message
      console.log(dialog.message());
      //accept alert
      await dialog.accept();
   })
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/javascript_alerts')
   //identify element with xpath then click
   const b = (await page.$x("//button[text()='Click for JS Confirm']"))[0]
   b.click()
}
confirmAlert()

Step 4 - 执行具有以下命令的代码。

Step 4 − Execute the code with the following command.

node <filename>

所以,在我们的示例中,我们将运行下面给出的命令 -

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

node testcase1.js
command has been successfully

命令成功执行后,确认警报文本 - 我是 JS 确认将打印在控制台。

After the command has been successfully executed, the confirm alert text - I am a JS Confirm gets printed in the console.

Puppeteer - Handling Drop-downs

在使用 Puppeteer 自动化测试时,我们可以在 UI 中处理下拉菜单。静态下拉菜单在 html 代码中用标签名 select 标识,其选项用标签名 option 标识。

We can handle drop downs in the UI while automating a test using Puppeteer. The static drop downs are identified in the html code with the tagname as select and its options have the tagname as option.

command has been successfully

Methods to Handle Dropdown

处理静态下拉菜单的一些方法 −

Some methods to work with static dropdowns −

select()

此方法用于从下拉菜单中选择一个选项。要选择的选项的值作为参数传递给此方法。

This method is used to select an option from the dropdown. The value of the option to be selected is passed as a parameter to this method.

Syntax

Syntax

其语法如下:

The syntax is as follows −

const page = await browser.newPage()
   const f = await page.$('[name="selType"]')
await f.select("subject")

我们还可从多选下拉菜单中选择多个选项。

We can also select multiple options from a multi-select dropdown.

Syntax

Syntax

其语法如下:

The syntax is as follows −

await f.select("subject", "name")

要从下拉菜单中获取选择值,我们必须使用 getProperty 方法并将值作为参数传递给此字段。

To obtain select value from the dropdown, we have to use the getProperty method and pass value as a parameter to this field.

const v = await (await n.getProperty("value")).jsonValue()
console.log(v)

type()

此方法用于从下拉菜单中选择一个选项。要选择的选项的值作为参数传递给此方法。

This method is used to select an option from the dropdown. The value of the option to be selected is passed as a parameter to this method.

Syntax

Syntax

其语法如下:

The syntax is as follows −

const page = await browser.newPage()
   const f = await page.$('[name="selType"]')
await f.type("subject")

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function dropDownHandle(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/tutor_connect/index.php')
   //identify dropdown then select an option by value
   const f = await page.$('[name="selType"]')
   await f.select("subject")
   //wait for sometime
   await page.waitForTimeout(4000)
   //get value selected
   const v = await (await f.getProperty("value")).jsonValue()
   console.log(v)
}
dropDownHandle()

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.j
terminal command

在成功执行命令后,将在控制台中打印从下拉列表中选择的选项的值 - 主题。

After the command has been executed successfully, the value of the option selected in the dropdown - subject is printed in the console.

Puppeteer - Locators

我们可以使用 Puppeteer 处理页面上的元素。一旦我们导航到一个网页,我们就需要与页面上的 web 元素交互,比如点击链接/按钮,在编辑框中输入文本,以此来完成我们的自动化测试用例。

We can handle elements on page with Puppeteer. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的首要任务是识别该元素。为了唯一地获取一个元素的属性,我们需要对其进行检查(右击该元素,然后选择“检查”选项)。ElementHandle 对象由方法创建,分别为:page .、page . $ $和 page . $ x。这些对象引用页面中的元素或标签。

For this, our first job is to identify the element. To get the property of an element uniquely we need to inspect it (right-click on the element then select the option Inspect). The ElementHandle objects are created by the methods - page.$, page.$$ and page.$x. These objects refer to an element or tag in a page.

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果 id 属性不存在,我们可以使用其他属性,例如 class、name 等。如果 id、name 和 class 等属性不存在,我们可以利用仅该标签专有的不同属性或属性及其值的组合来识别元素。为此,我们必须使用 xpath 表达式。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression.

Methods to locate elements

这些方法列在下面:

These methods are listed below −

page.$(locator value)

此方法产生带有 ElementHandle 的 Promise。ElementHandle 是已识别元素的一个对象。如果有多个元素具有相同定位值,则仅从页面的左上角返回第一个匹配的元素。

This method yields a Promise with the ElementHandle. The ElementHandle is an object of the identified element. If there are multiple elements having the same locator value, then only the first matching element from the top left corner of the page shall be returned.

page.$$(locator value)

此方法产生带有 ElementHandle 数组的 Promise。如果有多个元素具有相同定位值,则以数组形式返回所有匹配元素。

This method yields a Promise with an array of ElementHandle. If there are multiple elements having the same locator value, then all matching elements shall be returned in the form of an array.

page.$x(xpath value)

此方法产生带有 ElementHandle 数组的 Promise。如果有多个元素具有相同 xpath 值,则以数组形式返回所有匹配元素。如果有一个匹配的元素,则返回的数组将具有单个元素。

This method yields a Promise with an array of ElementHandle. If there are multiple elements having the same xpath value, then all matching elements shall be returned in the form of an array. In case, there is one matching element, then the array returned shall have a single element.

ElementHandle 方法,如 elementHandle.$、elementHandle.$$ 和 elementHandle.$x 可应用于一个元素。在这种情况下,应该在当前 ElementHandle 的 DOM 中搜索一个元素,而不在整个 DOM 中。

The ElementHandle methods like elementHandle.$, elementHandle.$$ and elementHandle.$x can be applied to an element. In that case, an element shall be searched within the DOM of the present ElementHandle and not in the entire DOM.

在下方给出的图像中,让我们举例说明一个具有 li 标记(具有 ul 父元素)和类属性值为标题的元素。

In the below given image, let us take the example of an element having the li tag(having a parent element ul) and class attribute value as heading.

要使用页面上的 ElementHandle 方法识别这个元素,表达式应如下所示:

To identify it using the ElementHandle method on the page, the expression should be as follows −

const n = await page.$(".heading")

要使用元素上的 ElementHandle 方法识别这个元素,表达式应如下所示:

To identify it using the ElementHandle method on an element, the expression should be −

const m = await page.$("ul")
const p = await m.$(".heading")

现在,参阅下面给出的一个具有 li 标签的元素的图片

Now, refer the image given below of an element having the li tag

toc chapters

Types of Locators

以下是 Puppeteer 中的定位符类型列表:

The types of locators in Puppeteer are listed below −

  1. ID

  2. Class

  3. Type

  4. Xpath

  5. Attribute

  6. Type

要使用上述定位符,我们应该基本了解 HTML 代码。让我们举例说明一个具有以下属性的编辑框:

To work with the above locators we should have the basic understanding of HTML code. Let us take an example of an edit box having the below properties −

types of locator

此处,input 是标签名称。HTML 中的标签可能有或没有属性。元素的类型、类、名称、ID 等是元素的属性。

Here, input is the tagname. A tag in HTML may or may not have attributes. The type, class, name, id and so on are the attributes of the element.

例如,在表达式 id = "gsc-i-id1" 中,= 左边的文本为属性名称 (id),= 右边的文本为属性值 (gsc-i-id1)。

For example, in the expression id = "gsc-i-id1", text to the left of = is the attribute name (id) and to the right of = is the attribute value (gsc-i-id1).

属性可能具有或不具有分配的值。此外,如果分配了一个值,那么它应该用双引号或单引号括起来。属性的值由开发人员根据自己的选择设置。

An attribute may or may not have a value assigned. Also, if a value is assigned, then it should be enclosed in double or single quotes. The value of an attribute is set by a developer as per his choice.

让我们举一个元素具有以下 HTML 代码的示例 -

Let us take an example of an element having the below html code −

elements

我们可以使用表达式 - 识别上图中的第一个复选框

We can identify the first checkbox in the above image, with the expression −

const n = await page.$("input[type='checkbox']")

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function checkBoxHandle(){
   //launch browser in headed mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/checkboxes')
   //identify element with xpath then click
   const n = await page.$("input[type='checkbox']")
   n.click()
   //wait for sometime
   await page.waitForTimeout(4000)
   //verify if checkbox is checked
   const v = await (await n.getProperty("checked")).jsonValue()
   console.log(v)
}
checkBoxHandle()

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

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

node <filename>

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

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

node testcase1.js
puppeteer terminal

在命令成功执行之后,将在控制台中打印布尔值 true。这是 getProperty("checked") 返回的值,因为已选中复选框,所以它返回 true。

After the command has been executed successfully, the boolean value true is printed in the console. This is returned by getProperty("checked") which returns true as the checkbox is selected.

Puppeteer - Xpath Functions

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果 id 属性不存在,我们可以使用其他属性,例如 class、name 等。如果 id、name 和 class 等属性不存在,我们可以利用仅该标签专有的不同属性或属性及其值的组合来识别元素。为此,我们必须使用 xpath 表达式。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression.

如果某个元素存在重复的属性或没有属性,则使用 text() 函数来识别该元素。为了使用 text() 函数,该元素一定要在页面上有可见的文本。

If there are duplicate attributes or no attribute for an element, then the function text() is used to identify an element. In order to use the text() function, it is mandatory that the element should have a text visible on the page.

Syntax

text() 函数的语法如下 -

The syntax for the use of text() function is as follows −

//tagname[text()='visible text on element']

如果某个元素的值或文本在本质上是部分动态的或非常长的,我们可以使用 contains() 函数。为了使用 contains() 函数,该元素一定要有时属性值或文本。

If the value of an element or the text is partially dynamic in nature or very lengthy, we can use the contains() function. In order to use the contains() function, it is mandatory that the element should either have an attribute value or a text.

Syntax

contains() 函数的语法如下 −

The syntax for the use of contains() function is as follows −

//tagname[contains(@attribute,'value')]
//tagname[contains(text(),'visible text on element')]

如果元素文本以特定文本开头,我们可以使用 starts-with() 函数。

If the text of an element begins with a particular text, we can use the starts-with() function to it.

Syntax

starts-with() 函数的语法如下 −

The syntax for the use of starts-with() function is as follows −

//tagname[starts-with(text(),'visible text on element')

在以上所有函数中,tagname 是可选的。我们可以使用符号 * 来代替 tagname。

In all the above functions, tagname is optional. Instead of tagname, we can use the symbol *.

在以下图片中,让我们借助显示的文本识别元素 - Library,然后单击它。

In the below image, let us identify the element - Library with the help of its displayed text and then click on it.

library

该元素的 xpath 为 //*[text()='Library']。

The xpath for the element shall be //*[text()='Library'].

在这里,我们使用 xpath 选择器工作,因此我们必须使用该方法:page.$x(xpath 值)。有关此方法的详细信息,请参阅章节 - Puppeteer 定位器。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The detail on this method is discussed in the Chapter - Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorFunTextXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with xpath function - text() then click
   const b = (await page.$x("//*[text()='Library']"))[0]
   b.click()
   //wait for sometime
   await page.waitForTimeout(4000)
   //obtain URL after click
   console.log(await page.url())
}
selectorFunTextXpath()

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
testcase

在成功执行该命令后,单击元素 Library 导航到的页面的 URL - https://www.tutorialspoint.com/tutorialslibrary.htm 将被打印在控制台中。

After the command has been successfully executed, the URL of the page navigated on clicking the element Library - https://www.tutorialspoint.com/tutorialslibrary.htm gets printed in the console.

Puppeteer - Xpath Attributes

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果 id 属性不存在,我们可以使用其他属性,例如 class、name 等。如果 id、name 和 class 等属性不存在,我们可以利用仅该标签专有的不同属性或属性及其值的组合来识别元素。为此,我们必须使用 xpath 表达式。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression.

如果带有单个属性的 xpath 表达式标识多个元素,我们可以使用 xpath 表达式中的多个属性来查找单个元素。

If an xpath expression with a single attribute identifies multiple elements, we can use more than one attribute in the xpath expression to locate a single element.

仅用一个属性编写 xpath 的格式如下−

The format for writing an xpath with only one attribute is as follows −

//tagname[@attribute='value']

对于多个属性,我们可以应用 AND 和 OR 条件。带有 AND 条件编写 xpath 的格式 −

For multiple attributes, we can apply AND and OR conditions. The format for writing an xpath with AND condition −

//tagName[@attribute1='value1'] [@attribute2='value2']

或者,

Or,

//tagName[@attribute1='value1' and @attribute2='value2']

带有 OR 条件编写 xpath 的格式如下−

The format for writing an xpath with OR condition is as follows −

//tagName[@attribute1='value1' or @attribute2='value2']

我们还可以通过对属性应用 NOT 条件来识别元素。带有 NOT 条件编写 xpath 的格式 −

We can also identify an element by applying the NOT condition on an attribute. The format for writing an xpath with NOT condition −

//tagname[not(@attribute='value')]

让我们借助 alt 属性识别页面上下面突出显示的徽标,然后单击它。

Let us identify the below highlighted logo on the page with the help of the alt attribute and then click on it.

tutorialspoint category

元素的 xpath 如下−

The xpath for the element shall be as follows −

//img[@alt='tutorialspoint'].

在这里,我们正在使用 xpath 选择器,因此我们必须使用以下方法:page.$x(xpath 值)。有关此方法的详细信息在 Puppeteer 定位器章节中讨论。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The detail on this method is discussed in the Chapter of Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorAttributeXpath(){
   //launch browser in headed mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/questions/index.php')
   //identify element with relative xpath then click
   const b = (await page.$x("//img[@alt='tutorialspoint']"))[0]
   b.click()
   //wait for sometime
   await page.waitForTimeout(4000)
   //obtain URL after click
   console.log(await page.url())
}
selectorAttributeXpath()

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
mac book

在成功执行命令后,单击徽标图像时导航到的页面的 URL - https://www.tutorialspoint.com/index.htm 将打印在控制台中。

After the command has been successfully executed, the URL of the page navigated on clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the console.

Puppeteer - Xpath Grouping

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果不存在 id 属性,我们可以使用 class、name 等其他属性。如果不存在 id、name、class 等属性,我们可以利用仅对该标签或属性及其值组合可用的不同属性来标识元素。为此,我们必须使用 xpath 表达式。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression.

通过利用索引从匹配元素的集合中获取一个元素称为组索引。如果 xpath 表达式识别出多个元素,那么我们可以使用组索引。

Obtaining one element from a collection of matching elements by utilising the index is known as the group index. If an xpath expression identifies multiple elements, then we can use the group index.

编写组索引的格式首先是 xpath 表达式,然后是括在 [] 中的索引号。它表示从 1 开始的 xpath 数组。函数 last() 用于指向 xpath 数组中的最后一个元素。

The format for writing a group index is first the xpath expression followed by the index number enclosed in []. It represents an xpath array with index starting from 1. The function last() is used to point to the last element in the xpath array.

Syntax

函数 last() 的语法如下所示 −

The syntax for the use of function last() is as follows −

(/table/tbody/tr/td[1]/input)[last()]

Syntax

函数 position() 用于获取 xpath 数组中特定位置的元素。语法如下所示 −

The function position() is used to obtain an element at a particular position in the xpath array. The syntax is as follows −

(/table/tbody/tr/td[1]/input)[position()=1]

上述 XPath 表达式应从所有匹配元素组中获取第一个元素。

The above xpath expression shall obtain the first element from the group of all the matching elements.

在下图中,我们标识高亮显示的编辑框并在其中输入一些文本。

In the below image, let us identify the highlighted edit box and input some text in it.

所以,XPath 表达式应如下所示:

So the xpath expression shall be as follows −

online education

在上述示例中,表中有两列(用 td 标记表示),其 tr 标记为父级。输入框出现在第一列。

In the above example, there are two columns (represented by td tags) in the table having the tr tag as their parent. The input box is present in the first column.

所以,XPath 表达式应如下所示:

So the xpath expression shall be as follows −

//table/tbody/tr/td[1]/input

在此,我们使用 XPath 选择器,所以我们必须使用下列方法:page.$x(xpath 值)。本章的 Puppeteer 定位符讨论了此方法的详细信息。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The details on this method are discussed in the Chapter of Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorGroupXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with group index xpath then enter text
   const f = (await page.$x("//table/tbody/tr/td[1]/input"))[0]
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //capture screenshot
   await page.screenshot({
      path: 'tutorialspoint.png'
   });
   //browser close
   await browser.close()
}
selectorGroupXpath()

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
tutorialspoint puppeteer

在成功执行命令之后,名为 tutorialspoint.png 的文件在页面目录中创建。它包含在浏览器中启动的页面截图,其文本为 Puppeteer。

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 with the text Puppeteer.

Puppeteer - Absolute Xpath

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果 id 属性不存在,我们可以使用其它属性,如 class、name 等。如果 id、name、class 等属性不存在,我们可以利用仅对该标签或属性及其值的组合可用的独特属性来识别元素。为此,我们必须使用 xpath 表达式。此外,如果页面上的元素是动态的,则 xpath 选择器可以作为选择器进行选择。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element. For this, we have to use the xpath expression. Also, if the element on a page is dynamic, then xpath selector can be a good choice as a selector.

Xpath 可以分为两种类型,即绝对和相对。绝对 xpath 以符号 / 开头,从根节点开始到我们要识别的元素。下面给出了一个示例。

Xpath can be of two types - absolute and relative. The absolute xpath begins with / symbol and starts from the root node upto the element that we want to identify. An example is given below for the same.

/html/body/div[1]/div/div[1]/a

让我们借助绝对 xpath 识别页面上下面突出显示的徽标,然后单击它。

Let us identify the below highlighted logo on the page with the help of the absolute xpath and then click on it.

puppeteer tutorialspoint

徽标的绝对 xpath 如下 −

The absolute xpath for the logo is as follows −

html/body/header/div[4]/div[1]/div[1]/a/img.

在这里,我们正在使用 xpath 选择器,因此我们必须使用以下方法:page.$x(xpath 值)。有关此方法的详细信息在 Puppeteer 定位器章节中讨论。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The detail on this method is discussed in the Chapter of Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorAbsoluteXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element with absolute xpath then click
   const b = (await page.$x("/html/body/header/div[4]/div[1]/div[1]/a/img"))[0]
   b.click()
   //wait for sometime
   await page.waitForTimeout(4000)
   //obtain URL after click
   console.log(await page.url())
}
selectorAbsoluteXpath()

Step 4 − 执行带有下面提到的命令的代码 −

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

node <filename>

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

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

node testcase1.js
puppeteer tutorialspoint1

在成功执行命令后,单击徽标图像时导航到的页面的 URL - https://www.tutorialspoint.com/index.htm 将打印在控制台中。

After the command has been successfully executed, the URL of the page navigated on clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the console.

Puppeteer - Relative Xpath

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果未提供 id 属性,我们可以使用其他属性(例如 class、name 等)。如果未提供 id、name 和 class 等属性,我们可以使用仅对该标签提供的独特属性,或其值和属性的组合来标识一个元素。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element.

为此,我们必须使用 xpath 表达式。此外,如果页面上的元素是动态的,那么 xpath 选择器可能是一个很好的选择器选择。

For this, we have to use the xpath expression. Also, if the element on a page is dynamic, then xpath selector can be a good choice as a selector.

Relative Xpath

Xpath 可分为两种类型 - 绝对和相对。相对 xpath 从要定位的元素开始,而不是从根开始。

Xpath can be of two types - absolute and relative. A relative xpath begins from the element to be located and not from the root.

它以 // 符号开头,表示任何后代。它的优势是,即使在 DOM 中删除或添加了一个元素,特定元素的相对 xpath 也不会受到影响。

It begins with the // symbol which refers to any descendant. Its advantage is that even if an element is deleted or added in the DOM, the relative xpath for a specific element remains unaffected.

要通过属性获取相对路径,xpath 表达式如下 -

To obtain a relative path by an attribute, the xpath expression is as follows −

//tagname[@attribute='value'].

让我们借助 alt 属性识别页面上下面突出显示的徽标,然后单击它。

Let us identify the below highlighted logo on the page with the help of the alt attribute and then click on it.

tutorialspoint1

元素的相对 xpath 如下所示

The relative xpath for the element is given below

//img[@alt='tutorialspoint'].

在这里,我们使用 xpath 选择器工作,因此我们必须使用该方法:page.$x(xpath 值)。有关此方法的详细信息,请参阅章节 - Puppeteer 定位器。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The detail on this method is discussed in the Chapter - Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorRelativeXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   a wait page.goto('https://www.tutorialspoint.com/questions/index.php')
   //identify element with relative xpath then click
   const b = (await page.$x("//img[@alt='tutorialspoint']"))[0]
   b.click()
   //wait for sometime
   //wait for sometime
   await page.waitForTimeout(4000)
   //obtain URL after click
   console.log(await page.url())
}
selectorRelativeXpath()

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
terminal

在成功执行命令后,单击徽标图像时导航到的页面的 URL - https://www.tutorialspoint.com/index.htm 将打印在控制台中。

After the command has been successfully executed, the URL of the page navigated on clicking the logo image - https://www.tutorialspoint.com/index.htm gets printed in the console.

Puppeteer - Xpath Axes

为了唯一地确定一个元素,我们可以使用 html 标签内的任何属性或使用 html 标签上的多个属性的组合。通常使用 id 属性,因为它对于页面是唯一的。

To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

但是,如果未提供 id 属性,我们可以使用其他属性(例如 class、name 等)。如果未提供 id、name 和 class 等属性,我们可以使用仅对该标签提供的独特属性,或其值和属性的组合来标识一个元素。

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element.

为此,我们必须使用 xpath 表达式。此外,如果页面上的元素是动态的,那么 xpath 选择器可能是一个很好的选择器选择。

For this, we have to use the xpath expression. Also, if the element on a page is dynamic, then xpath selector can be a good choice as a selector.

xpath 是双向的,这意味着我们可以从父元素遍历到子元素,也可以从子元素遍历到父元素。下面链接中提供了 xpath 轴的详细信息 −

The xpath is bi-directional which means we can traverse from the parent to the child element and also from the child to the parent element. The details of xpath axes shall be available in the below link −

在下图中,我们识别高亮的编辑框,并获取其类属性的值 - gsc-input。

In the below image, let us identify the highlighted edit box and obtain the value of its class attribute - gsc-input.

highlighted edit box

在上述示例中,表中有两列(用 td 标记表示),其 tr 标记为父级。输入框出现在第一列。

In the above example, there are two columns (represented by td tags) in the table having the tr tag as their parent. The input box is present in the first column.

所以,XPath 表达式应如下所示:

So the xpath expression shall be as follows −

//table/tbody/tr/child::td.

在此,我们使用 XPath 选择器,所以我们必须使用下列方法:page.$x(xpath 值)。本章的 Puppeteer 定位符讨论了此方法的详细信息。

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The details on this method are discussed in the Chapter of Puppeteer Locators.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorAxesXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with xpath axes
   const n = (await page.$x("//table/tbody/tr/child::td"))[0]
   // get value of class attribute
   let v = await page.$eval("input", n => n.getAttribute("class"))
   console.log(v)
}
selectorAxesXpath()

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
node testcase1

在成功执行命令后,元素 - gsc-input 的类属性值将打印在控制台中。

After the command has been successfully executed, the value of the class attribute for the element - gsc-input gets printed in the console.

Puppeteer - Type Selector

一旦我们导航到一个网页,我们就必须与页面上可用的网络元素交互,例如单击链接/按钮、在编辑框中输入文本等等,才能完成我们的自动化测试用例。

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的第一项工作是识别元素。如果一个标签在页面中仅使用一次,我们可以将其用作类型选择器。如果有多个元素具有相同的标签,则页面上仅匹配的第一个元素会被识别。

For this, our first job is to identify the element. If a tag is used only one time in a page, we can use it as a type selector. If there are multiple elements with the same tag, only the first matching element on the page shall be identified.

Syntax

类型选择器的语法如下 −

The syntax for type selector is as follows −

const n = await page.$("h4")

在下面的示例中,让我们识别具有标签名 h4 的突出显示的元素,并获取其文本 - You are browsing the best resource for Online Education。

In the below example, let us identify the highlighted element having tagname h4 and obtain its text - You are browsing the best resource for Online Education.

browsing

首先,按照 Puppeteer 的基本测试章节执行步骤 1 到 2,步骤如下:

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which is 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 pt= require('puppeteer')
async function selectorType(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with type selector
   const n = await page.$("h4")
   //obtain text
   const text = await (await n.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
selectorType()

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
best resource

在成功执行该命令后,元素上的文本 - You are browsing the best resource for Online Education 被打印在控制台中。

After the command has been successfully executed, the text on the element - You are browsing the best resource for Online Education gets printed in the console.

Name Selector and Class Name Selector

让我们从了解名称选择器开始。

Let us begin by learning about name selector.

Name Selector

一旦我们导航到一个网页,我们就必须与页面上可用的网络元素交互,例如单击链接/按钮、在编辑框中输入文本等等,才能完成我们的自动化测试用例。

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的第一项工作是识别元素。如果 name 属性的值在一页中只使用一次,我们可以将其用作名称选择器。如果存在多个具有相同名称的元素,则只识别页面上的第一个匹配元素。

For this, our first job is to identify the element. If a value of the name attribute is used only one time in a page, we can use it as a name selector. If there are multiple elements with the same name, only the first matching element on the page shall be identified.

Syntax

名称选择器的语法如下所示:

The syntax for name selector is as follows −

const f = await page.$('[name="search"]')

让我们识别下方图像中高亮的编辑框并输入文本 -

Let us identify the edit box highlighted in the below image and enter text −

awake

上图中突出显示的元素的 name 属性值为搜索。上述元素的名称选择器表达式应为 [name="search"]。

The element highlighted in the above image has the name attribute value as search. The name selector expression for the above element shall be [name="search"].

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorName(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage();
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify edit box with name
   const f = await page.$('[name="search"]')
   //enter text
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //browser close
   await browser.close()
}
selectorName()

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

Class Name Selector

一旦我们导航到一个网页,我们就必须与页面上可用的网络元素交互,例如单击链接/按钮、在编辑框中输入文本等等,才能完成我们的自动化测试用例。

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的第一项工作是识别元素。如果一个类名在页面中仅被使用一次,我们就可以将它用作类名选择器。如果存在具有相同类名的多个元素,则只识别页面上的第一个匹配元素。

For this, our first job is to identify the element. If a class name is used only one time in a page, we can use it as a class name selector. If there are multiple elements with the same class name, only the first matching element on the page shall be identified.

Syntax

类名选择器的语法如下所示:

The syntax for class name selector is as follows −

const n = await page.$(".txtloc")

在下面的示例中,让我们识别具有类名 heading 的突出显示的元素并获取其文本 - 关于 Tutorialspoint。

In the below example, let us identify the highlighted element having class name heading and obtain its text - About Tutorialspoint.

about tutorialspoint

上述元素的 id 选择器表达式应为 .heading。

The id selector expression for the above element shall be .heading.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function getText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element with class name
   const f = await page.$(".heading")
   //obtain text
   const text = await (await f.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
getText()

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
base terminal

命令执行成功后,元素 - About Tutorialspoint 的文本将打印在控制台中。

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.

Puppeteer - Id Selector

一旦我们导航到一个网页,我们就必须与页面上可用的网络元素交互,例如单击链接/按钮、在编辑框中输入文本等等,才能完成我们的自动化测试用例。

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的首要任务是识别元素。id 属性在页面中通常是唯一的,可用作 id 选择器。与所有选择器相比,它是一个非常有用的定位器,并加快了自动化测试的执行速度。

For this, our first job is to identify the element. An id attribute is generally unique in a page and can be used as an id selector. It is a very useful locator and speeds up the execution of automation tests in comparison to all the selectors.

Syntax

id 选择器的语法如下 -

The syntax for Id selector is as follows −

const n = await page.$("#loc")

在下面的示例中,让我们识别带有 id txtSearchText 的高亮元素并输入文本。

In the below example, let us identify the highlighted element having id txtSearchText and enter text into it.

tutor connect

上述元素的 id 选择器表达式应为 #txtSearchText。

The id selector expression for the above element shall be #txtSearchText.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorId(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage();
   //launch URL
   await page.goto('https://www.tutorialspoint.com/tutor_connect/index.php')
   //identify element with id
   const f = await page.$("#txtSearchText")
   //enter text
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //browser close
   await browser.close()
}
selectorId()

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

Puppeteer - Attribute Selector

一旦我们导航到一个网页,我们就必须与页面上可用的网络元素交互,例如单击链接/按钮、在编辑框中输入文本等等,才能完成我们的自动化测试用例。

Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case.

为此,我们的第一步是识别元素。如果某属性及其值在标签中仅使用一次,我们可以将其用作一个属性选择器。如果多个元素都具有相同的属性值,则在该页面上 shall 识出第一个匹配的元素。

For this, our first job is to identify the element. If an attribute and its value is used only one time in a tag, we can use it as an attribute selector. If there are multiple elements with the same attribute value, only the first matching element on the page shall be identified.

Syntax

属性选择器的语法如下 -

The syntax for attribute selector is as follows −

const f = await page.$("ul[name='val']")

此处,ul 为标签名,val 为 name 属性设定的值。

Here, ul is the tagname and val is the value set for the name attribute.

在下图中,让我们获得高亮显示元素的 - About Tutorialspoint 的文本 -

In the below image, let us obtain the text - About Tutorialspoint for the highlighted element −

li heading

上述元素的属性选择器表达式应为 li[class='heading']。

The attribute selector expression for the above element shall be li[class='heading'].

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function selectorAttribute(){
   //launch browser in headed mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element with attribute selector
   const n = await page.$("li[class='heading']")
   //obtain text
   const t = await (await n.getProperty('textContent')).jsonValue()
   console.log("Obtained text is: " + t)
}
selectorAttribute()

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
about

命令执行成功后,元素 - About Tutorialspoint 的文本将打印在控制台中。

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.

Puppeteer - Handling Links/Button

Puppeteer 能够处理页面上的链接/按钮。在单击元素之前,我们必须能够使用任何定位符唯一地识别它。在 Puppeteer 中,我们只能在元素尺寸大于 0 像素时单击它。

Puppeteer is capable of handling a link/button on a page. Before clicking an element we must be able to uniquely identify it with the help of any of the locators. In Puppeteer, we can click an element only if its dimensions are greater than zero pixel.

在下图中,我们将单击下面突出显示的链接 - 订阅高级计划,其标签名为 h1:

In the below image, we shall click on the below highlighted link - Subscribe to Premium Plan having tagname as h1 −

element h1

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function clickElement(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element then click
   await page.click('h1');
   //get page title after click
   console.log(await page.title())
}
clickElement()

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
paid subscription

在命令成功执行后,单击链接后获得的标题 - Tutorials Point 付费订阅包 - Tutorialspoint 被打印到控制台中。

After the command has been successfully executed, the title - Tutorials Point Paid Subscription Packages - Tutorialspoint obtained after clicking the link - Subscribe to Premium Plan gets printed in the console.

Handling Edit Boxes & Checkboxes

让我们来了解 Puppeteer 如何处理编辑框。

Let us understand how Puppeteer can handle edit boxes.

Handling Edit Boxes

Puppeteer 能够处理编辑框。编辑框具有 HTML 标签 input,其 type 属性的值设置为文本。

Puppeteer is capable of handling edit boxes. An edit box has an HTML tag as input and its type attribute is set to the value as text.

下面列出了一些使用编辑框的方法:

Some methods to work with edit boxes are listed below −

type()

此方法用于将文本输入到编辑框和文本区域,而不会替换已存在的内容。

This method is used to input text into an edit box and text area without replacing the already present content.

Syntax

Syntax

type() 的语法如下:

The syntax for type() is as follows −

const n = await page.$("#txt")
await n.type("Puppeteer")

我们可以在编辑框中输入文本并进行一些延迟。这可以通过添加参数 {delay:time interval} 来完成。时间间隔以毫秒表示。

We can enter text in an edit box with some delay. This is done by adding the parameter {delay:time interval}. The time interval is expressed in the milliseconds.

Syntax

Syntax

语法如下:

The syntax for the same is as follows −

await page.type("[class='loc']", "Tutorialspoint", {delay:700})

要删除在编辑框中输入的文本,我们必须对该字段执行三次单击事件(使用参数 clickCount),然后按退格键。这类似于在编辑框中选择所有值,然后按退格键。

To delete a text entered in an edit box, we have to perform the click event three times on the field(with the parameter clickCount) and then press backspace. It is similar to selecting all values in an edit box and then pressing backspace.

Syntax

Syntax

语法如下所示:−

The syntax is given below −

const n = await page.$("#txt")
await n.type("Puppeteer")
await n.click({clickCount: 3});
await page.keyboard.press('Backspace')

若要获得在编辑框中输入的值,我们必须使用 getProperty 方法并将值作为参数传递到该字段。

To get value entered in an edit box, we have to use the getProperty method and pass value as a parameter to this field.

const v = await (await n.getProperty("value")).jsonValue()
console.log(v)

在以下图像中,让我们输入文本 Puppeteer,然后将其清除。

In the below image, let us input the text Puppeteer and then clear it.

text puppeteer

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

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which is 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 pt= require('puppeteer')
async function enterText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage();
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify edit box
   const f = await page.$("#gsc-i-id1")
   //enter text
   f.type("Puppeteer")
   //clear text entered
   await f.click({clickCount: 3})
   //wait for sometime
   await page.waitForTimeout(4000)
   await page.keyboard.press('Backspace')
   //browser close
   await browser.close()
}
enterText()

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

Handling Checkboxes

在使用 Puppeteer 自动化测试时,我们可以在 UI 中处理复选框。HTML 代码中的复选框用标签名称 input 和类型 checkbox 标识。

We can handle checkboxes in the UI while automating a test using Puppeteer. The checkboxes are identified in the html code with the tagname as input and type as checkbox.

handling checkboxes

以下是一些用于处理复选框的方法:

Some methods to work with checkboxes are given below −

click()

用于勾选和取消勾选复选框。此方法是 ElementHandle 类的一部分。

It is used to check and uncheck a checkbox. This method is a part of the ElementHandle class.

Syntax

Syntax

click() 的语法如下所示:

The syntax of click() is as follows −

const n = await page.$("#txt")
n.click()

若要验证是否勾选了一个复选框,我们必须使用 getProperty 方法并将值作为参数传递到该字段。它返回一个布尔值(勾选则为真,否则为假)。

To verify if a checkbox is checked, we have to use the getProperty method and pass value as a parameter to this field. It returns a Boolean value(true if checked, false if not).

const v = await (await n.getProperty("checked")).jsonValue()
console.log(v)

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function checkBoxHandle(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/checkboxes')
   //identify element then click
   const n = await page.$("input[type='checkbox']")
   n.click()
   //wait for sometime
   await page.waitForTimeout(4000)
   //verify if checkbox is checked
   const v = await (await n.getProperty("checked")).jsonValue()
   console.log(v)
}
checkBoxHandle()

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
base

在成功执行命令后,将在控制台中打印布尔值 true。这是getProperty("checked") 返回的值,当选中复选框时,它返回 true。

After the command has been executed successfully, the boolean value true is printed in the console. This is returned by the getProperty("checked") which returns true as the checkbox is selected.

Puppeteer - Handling Frames

html 代码中的框架由框架/iframe 标签表示。Puppeteer 可以通过从主页切换到框架来处理框架。若要处理框架内部的元素,我们首先必须借助定位器识别框架。使用内容框架方法访问框架内的元素。

The frames in an html code are represented by the frames/iframe tag. Puppeteer can handle frames by switching from the main page to the frame. To work with elements inside a frame, first we have to identify the frame with the help of locators. The method contentFrame is used to access the elements inside the frame.

Syntax

处理框架的语法如下所示:

The syntax to handle frames is as follows −

const f = await page.$("frame[name='frame-bottom']")
const m = await f.contentFrame()

让我们看看框架内元素的 html 代码并获取其中的文本 - BOTTOM。

Let us see the html code of an element inside a frame and obtain the text - BOTTOM inside it.

bottom

上面图像中突出显示的标签是 frame,其名称属性的值是 frame-bottom。

The tagname highlighted in the above image is frame and the value of its name attribute is frame-bottom.

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function frameHandle(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://the-internet.herokuapp.com/nested_frames')
   //identify frame
   const f = await page.$("frame[name='frame-bottom']")
   //move to frame
   const x = await f.contentFrame();
   //identify element inside frame
   const n = await x.$("body")
   //get text
   const v = await (await n.getProperty("textContent")).jsonValue()
   console.log(v)
}
frameHandle()

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

Step 4 − Execute the code with the command −

node <filename>

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

So in our example, we shall run the command −

node testcase1.js
terminal console

成功执行命令后,框架 - BOTTOM 内的文本将打印在控制台中。

After the command has been successfully executed, the text within the frame - BOTTOM gets printed in the console.

Puppeteer - Keyboard Simulation

Puppeteer 可以执行键盘模拟操作,如按下键盘上的键、按下向上键、向下键等等。所有这些都是使用键盘方法完成的。

Puppeteer can perform keyboard simulation actions like pressing a key in the keyboard, pressing the up, down keys, and so on. All these are done using the keyboard method.

Keyboard Methods

以下是一些键盘方法:

Some of the keyboard methods are as follows −

keyboard.press()

此方法用于模拟按键。要按下的键作为参数传递给此方法。

This method is used to simulate a key press. The key to be pressed is passed as a parameter to this method.

其语法如下:

The syntax is as follows −

Syntax

Syntax

keyboard.press('Enter')

keyboard.type()

此方法用于模拟从键盘输入文本。要输入的文本作为参数传递给此方法。

This method is used to simulate entering text from the keyboard. The text to be entered is passed as a parameter to this method.

其语法如下:

The syntax is as follows −

Syntax

Syntax

keyboard.type('Puppeteer')

keyboard.sendCharacter()

它与キーボード.类型()相同。

It is same as keyboard.type().

其语法如下:

The syntax is as follows −

Syntax

Syntax

keyboard.sendCharacter('Puppeteer')

keyboard.up()

这种方法用于模拟从键盘按下向上箭头。

This method is used to simulate pressing the up arrow from the keyboard.

其语法如下:

The syntax is as follows −

Syntax

Syntax

keyboard.up()

keyboard.down()

这种方法用于模拟从键盘按下向下箭头。

This method is used to simulate pressing the down arrow from the keyboard.

其语法如下:

The syntax is as follows −

Syntax

Syntax

keyboard.down()
keyboard down

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function keyboradSimulation(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify edit box with id
   const f = await page.$("#gsc-i-id1")
   //enter text
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //press Enter
   await page.keyboard.press('Enter')
   //wait for sometime
   await page.waitForTimeout(4000)
   //identify element
   const t = await page.$(".gsc-result-info")
   //obtain text
   const text = await (await t.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
keyboradSimulation()

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
about 39 results

在命令成功执行后,在输入 Puppeteer - About 39 results (0.15 seconds) 后按 Enter 获得的文本将打印在控制台中。

After the command has been successfully executed, the text obtained on pressing Enter after entering Puppeteer - About 39 results (0.15 seconds) gets printed in the console.

Puppeteer - Getting Element Text

我们可以在 Puppeteer 中获取元素文本。这通过借助 textContent 属性来完成。该元素的该属性作为参数传递给了 getProperty 方法。

We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.

Syntax

获取元素文本的语法如下:

The syntax of getting element text is as follows −

const n = await page.$("#txt")
const t = await (await n.getProperty('textContent')).jsonValue()

在下图中,让我们获得高亮显示元素的 - About Tutorialspoint 的文本 -

In the below image, let us obtain the text - About Tutorialspoint for the highlighted element −

about tutorialspoint for highlighted element

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function getText(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/about/about_careers.htm')
   //identify element
   const f = await page.$("[class='heading']")
   //obtain text
   const text = await (await f.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
getText()

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
console

命令执行成功后,元素 - About Tutorialspoint 的文本将打印在控制台中。

After the command has been successfully executed, the text of the element - About Tutorialspoint gets printed in the console.

Puppeteer - Getting Element Attribute

我们能够使用 Puppeteer 获得元素的属性值。这些属性在 HTML 标记中添加。它们被用于描述元素的属性。一个属性及其值在键值对中定义。

We can get attribute values of an element using Puppeteer. The attributes are added within the HTML tag. They are used to describe the properties of an element. An attribute and its value are defined in a key-value pair.

我们取一个具有以下属性的编辑框示例 -

Let us take an example of an edit box having the below properties −

getting element attribute

此处,input 是标签名。HTML 中的标签可能有也可能没有属性。类型、类、名称、ID 等是此元素的属性。例如,在 id = gsc-i-id1 中,= 左侧的文本是属性名称(即 id),而 = 右侧是属性值(即 gsc-i-id1)。

Here, input is the tagname. A tag in HTML may or may not have attributes. The type, class , name, id and so on are the attributes of this element. For example, in id = gsc-i-id1, text to the left of = is the attribute name(i.e id) and to the right of = is the attribute value(i.e gsc-i-id1).

属性可能具有或不具有分配的值。此外,如果分配了一个值,那么它应该用双引号或单引号括起来。属性的值由开发人员根据自己的选择设置。

An attribute may or may not have a value assigned. Also, if a value is assigned, then it should be enclosed in double or single quotes. The value of an attribute is set by a developer as per his choice.

Methods for Element Attribute

获取元素属性的方法如下所列 -

The ways to obtain an element attribute are listed below −

getAttribute()

此方法用于获取该方法作为参数传递的属性的值。

This method is used to get the value of the attribute which is passed as a parameter to this method.

Syntax

Syntax

其语法如下:

The syntax is as follows −

let v = await page.$eval("input", element=> element.getAttribute("class"))

element.<attribute name>

Syntax

Syntax

其语法如下:

The syntax is as follows −

let v = await page.$eval("input", element=> element.class)

element.getProperty()

此方法用于获取该方法作为参数传递的属性的值。

This method is used to get the value of the attribute which is passed as a parameter to this method.

其语法如下:

The syntax is as follows −

Syntax

Syntax

const n = await page.$("#txt")
const t = await (await n.getProperty('textContent')).jsonValue()

在下图中,我们识别高亮的编辑框,并获取其类属性的值 - gsc-input。

In the below image, let us identify the highlighted edit box and obtain the value of its class attribute - gsc-input.

class attribute

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function getElementAttribute(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with id
   const n = await page.$("#gsc-i-id1")
   //get class attribute
   let v = await page.$eval("input", n => n.getAttribute("class"))
   console.log(v)
}
getElementAttribute()

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
element gsc input

在成功执行命令后,元素 - gsc-input 的类属性值将打印在控制台中。

After the command has been successfully executed, the value of the class attribute for the element - gsc-input gets printed in the console.

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.

Puppeteer - Disable JavaScript

我们可以使用 Puppeteer 禁用 JavaScript。为此,我们必须根据其类型阻止请求/响应。让我们尝试禁用 JavaScript 来启动页面。

We can disable JavaScript using Puppeteer. For this, we have to block the requests/response based on its type. Let us make an attempt to launch a page by disabling JavaScript.

首先,按照人偶基本测试章节执行步骤 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 pt = require('puppeteer')
pt.launch().then(async browser => {
//browser new page
   const page = await browser.newPage()
   //monitor requests
   await page.setRequestInterception(true)
   //check resourceType is script
   page.on('request', request => {
      if (request.resourceType() === 'script')
         request.abort();
      else
         request.continue();
   })
   //launch application
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //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

Puppeteer - Synchronization

Puppeteer Page 类包含实现同步的方法。这些方法用于等待页面上的事件/元素。它等待指定条件满足(为真值)。例如,我们经常等待在页面上出现文本。

Puppeteer Page class contains methods to achieve synchronization. These methods are used to wait for an action/element on the page. It waits for criteria to be met (a true value). For example, we often wait for a text to appear on the page.

Synchronization methods

以下列出 Puppeteer 中的同步方法−

The synchronization methods in Puppeteer are listed below −

waitFor

此方法用于在解决 Promise 前等待一定时间。

This method is used to wait for a specific amount of time before resolving a Promise.

Syntax

Syntax

其语法如下:

The syntax is as follows −

await page.waitFor(4000)

waitForSelector

此方法用于等待元素出现在网页上或从网页上消失。

This method is used to wait for an element to be visible or disappear from the webpage.

Syntax

Syntax

其语法如下:

The syntax is as follows −

page.waitForSelector(
   selector,
   {options : value}
)

waitForSelector 接受两个参数。第一个参数是元素的选择器值。第二个参数是选项数组。选项如下所列−

The waitForSelector accepts two parameters. The first parameter is the selector value of an element. The second parameter is the array of options. The options are listed below −

  1. Visible − Puppeteer shall wait till an element locator is visible on the page. The default value is false.

  2. Hidden − Puppeteer shall wait till an element locator is hidden from the page. The default value is false.

  3. Timeout − The maximum wait time for an element in milliseconds. The default value is 30000. If the timeout is set to zero, this is discarded.

可以使用以下给出的方法修改默认等待时间−

The default wait time can be modified by using the method given below −

page.setDefaultTimeout(6000)

例如,

For example,

let l = await page.waitForSelector( "#ltxt", { visible: true } )

waitForXpath

此方法用于等待由 xpath 识别的元素/元素出现在网页上或从网页上消失。

This method is used to wait for element/elements identified by xpath to be visible or disappear from the webpage.

Syntax

Syntax

其语法如下:

The syntax is as follows −

page.waitXpath(
   Xpath value,
   {options : value}
)

waitForXpath 接受两个参数。第一个参数是元素的 xpath 选择器值。第二个参数是选项数组。选项如下所列 −

The waitForXpath accepts two parameters. The first parameter is the xpath selector value of an element. The second parameter is the array of options. The options are listed below −

  1. Visible − Puppeteer shall wait till an element locator is visible on the page. The default value is false.

  2. Hidden − Puppeteer shall wait till an element locator is hidden from the page. The default value is false.

  3. Timeout − The maximum wait time for an element in milliseconds. The default value is 30000. If the timeout is set to zero, this is discarded.

可以使用以下方法修改默认等待时间 −

The default wait time can be modified using the below method −

page.setDefaultTimeout(6000)

例如,

For example,

let x= await page.waitForXPath( "//*[@name='search']", { visible: true } )

waitForFunction

此方法用于等到所提供的函数返回 true 值。

This method is used to wait till the provided function returns a true value.

Syntax

Syntax

其语法如下:

The syntax is as follows −

page.waitForFunction(
   pagefunction,
   {options : value},
   pagefunction args
)

waitForFunction 具有以下参数 −

The waitForFunction has the following parameters −

pagefunction 是要执行的函数。例如,

The pagefunction is the function to be executed. For example,

page.waitForFunction("document.getElementById('txt').value === 'text'", {})

此函数将一直等待,直到含 ID 元素的值等于文本。

This function shall wait till the value of the element with id is equal to text.

该选项是等待参数的数组。它们包括 - polling(pagefunction 应在多少毫秒内执行一次)和 timeout(Puppeteer 应等待 pagefunction 返回 true 值的最长时间)。

The option is an array of waiting parameters. They are - polling (the interval at which the pagefunction should be executed in milliseconds) and timeout (The maximum time the Puppeteer shall wait for the pagefunction to return true value).

pagefunction args 是传递给 pagefunction 函数的参数。

The pagefunction args are the arguments passed to the pagefunction function.

在下图中,让我们输入文本 - Puppeteer,然后按 Enter。

In the below image, let us input text - Puppeteer and then press Enter.

pagefunction

按 Enter 后,将打开一个新窗口,其中包含文本 - 约 39 个搜索结果。

After pressing Enter, a new window having the search results with text - About 39 results should open up.

59 results

首先,按照人偶基本测试章节执行步骤 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 pt= require('puppeteer')
async function waitImplementation(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify edit box
   const f = await page.$("#gsc-i-id1")
   //enter text
   f.type("Puppeteer")
   //wait for sometime
   await page.waitForTimeout(4000)
   //press Enter
   await page.keyboard.press('Enter')
   //wait for an element xpath
   await page.waitForXPath("//div[@class='gsc-result-info']")
   //identify element
   const t = await page.$(".gsc-result-info")
   //obtain text
   const text = await (await t.getProperty('textContent')).jsonValue()
   console.log("Text is: " + text)
}
waitImplementation()

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
console1

Puppeteer - Capture Screenshot

在使用 Puppeteer 开发的自动化测试上运行时,我们可以使用屏幕截图方法捕捉屏幕截图。如果遇到应用程序错误、测试用例失败等情况,则通常会捕捉屏幕截图。

We can capture screenshots while working on automation tests developed in Puppeteer using the screenshot method. A screenshot is generally captured if we encounter an application error, a failure in a test case, and so on.

Syntax

Puppeteer 截取屏幕截图的语法如下 -

The syntax to capture screenshot in Puppeteer is as follows −

await page.screenshot({
   path: 'tutorialspoint.png'
})

此处,要保存屏幕截图的路径作为参数传递给该方法。这样,只会截取网页的可见部分。要截取整个页面的屏幕截图,我们必须传递另一个参数 fullPage,并将其值设为 true。

Here, the path where the screenshot is to be saved is passed as a parameter to the method. With this, only the viewable part of the web page shall be captured. To capture the full page screenshot, we have to pass another parameter called the fullPage and set its value to true.

Syntax

其语法如下:

The syntax is as follows −

await page.screenshot({
   path: 'tutorialspoint.png', fullPage: true
})

让我们截取下面页面的屏幕截图 -

Let us capture the screenshot of the below page −

screenshot

首先,按照人偶基本测试章节执行步骤 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');
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 command given below −

node <filename>

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

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

node testcase1.js
launched in the browser

命令成功执行后,将在页面目录中创建一个名为 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.