javascript - 使用 Puppeteer,如何从 <h1> 标签中获取文本?

标签 javascript node.js google-chrome-devtools puppeteer

我正在使用 CucumberJS 和 Puppeteer。我很难从 <h1> 中提取文本标签。

ember .hbs 代码是:

<div class="grid__cell" data-test-foobar4="true">
    <h1 class="ao-headline u-font--light" data-test-foobar3="true">{{pageTitle}}</h1>
</div>

我正在使用 HTML data-我的选择器的标签,因为 EmberJS 使用动态 id。

// Read page table title
async verifyTestTileForList() {
    const textContent = await this.page.evaluate(() => document.body.querySelector('[data-test-foobar3="true"]').textContent);
    console.log('Page title = ' + textContent);
}

当我运行它时,我得到:

Error: Evaluation failed: TypeError: Cannot read property 'textContent' of null

这对我来说没有意义。我查看 HTML,我看到:

<h1 data-test-foobar3="true" class="ao-headline u-font--light">Imports</h1>

我哪里错了?

最佳答案

该元素很可能是动态生成的,因此您应该等待带有 page.waitForSelector() 的元素。在尝试抓取 textContent 之前:

await page.waitForSelector('[data-test-foobar3="true"]');
const textContent = await page.evaluate(() => document.querySelector('[data-test-foobar3="true"]').textContent);
console.log('Page title = ' + textContent);

关于javascript - 使用 Puppeteer,如何从 <h1> 标签中获取文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52122871/

相关文章:

javascript - 手动选择铁列表项目时出错

JavaScript 上传相同文件

node.js - Docker 运行失败 "return process.dlopen(module, path.toNamespacedPath(filename));"

javascript - Web 开发人员如何查看用户控制台错误?

javascript - Skycons 未显示

javascript - 使用异步调用在 for 循环中构建数组

google-chrome-devtools - 这些是什么 No beacon、Next in ... Chrome 开发者控制台中的日志消息

javascript - 检测提示中的无效号码

javascript - 无法使用 Chrome devtools 移动模式打开选择

javascript - 更新html中iframe链接的href