Puppeteer - 获取元素文本


我们可以在 Puppeteer 中获取元素文本。这是在 textContent 属性的帮助下完成的。元素的此属性作为参数传递给 getProperty 方法。

句法

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

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

在下图中,让我们获取突出显示元素的文本 - About Tutorialspoint -

关于突出显示元素的 Tutorialspoint

首先,请按照《Puppeteer 基本测试》一章中的步骤 1 至 2 进行操作,如下所示 -

步骤 1 - 在创建 node_modules 文件夹的目录中创建一个新文件(Puppeteer 和 Puppeteer 核心的安装位置)。

Puppeteer 安装的详细信息将在 Puppeteer 安装章节中讨论。

右键单击创建 node_modules 文件夹的文件夹,然后单击“新建文件”按钮。

节点模块

步骤 2 - 输入文件名,例如 testcase1.js。

测试用例1.JS

步骤 3 - 在创建的 testcase1.js 文件中添加以下代码。

//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()

步骤 4 - 使用下面给出的命令执行代码 -

node <filename>

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

node testcase1.js
安慰

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