Puppeteer - 获取元素文本
我们可以在 Puppeteer 中获取元素文本。这是在 textContent 属性的帮助下完成的。元素的此属性作为参数传递给 getProperty 方法。
语法
获取元素文本的语法如下 −
const n = await page.$("#txt") const t = await (await n.getProperty('textContent')).jsonValue()
在下图中,让我们获取突出显示元素的文本 - 关于 Tutorialspoint −

首先,按照 Puppeteer 基本测试章节中的步骤 1 到 2 进行操作,如下所示 −
步骤 1 −在创建 node_modules 文件夹的目录(安装 Puppeteer 和 Puppeteer 核心的位置)内创建一个新文件。
有关 Puppeteer 安装的详细信息,请参阅 Puppeteer 安装一章。
右键单击创建 node_modules 文件夹的文件夹,然后单击新建文件按钮。

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

步骤 3 −在创建的 testcase1.js 文件中添加以下代码。
//Puppeteer 库 const pt= require('puppeteer') async function getText(){ //以 headless 模式启动浏览器 const browser = await pt.launch() //浏览器新页面 const page = await browser.newPage() //启动 URL await page.goto('https://www.tutorialspoint.com/about/about_careers.htm') //识别元素 const f = await page.$("[class='heading']") //获取文本 const text = await (await f.getProperty('textContent')).jsonValue() console.log("Text is: " + text) } getText()
步骤 4 − 使用下面给出的命令执行代码 −
node <filename>
因此,在我们的示例中,我们将运行以下命令 −
node testcase1.js

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