Puppeteer 简明教程

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.