Puppeteer 简明教程

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.