我正在使用 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/