最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Puppeteer, how do you get text from an <h1> tag? - Stack Overflow

programmeradmin7浏览0评论

I'm using CucumberJS & Puppeteer. I am having a difficult time extracting the text from an <h1> tag.

The ember .hbs code is:

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

I'm using HTML data- tags for my selectors since EmberJS uses dynamic id's.

// 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);
}

When I run this, I get:

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

Which doesn't make sense to me. I look at the HTML, and I see:

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

Where am I going wrong?

I'm using CucumberJS & Puppeteer. I am having a difficult time extracting the text from an <h1> tag.

The ember .hbs code is:

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

I'm using HTML data- tags for my selectors since EmberJS uses dynamic id's.

// 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);
}

When I run this, I get:

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

Which doesn't make sense to me. I look at the HTML, and I see:

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

Where am I going wrong?

Share Improve this question edited Sep 6, 2018 at 4:11 Grant Miller 29.1k16 gold badges156 silver badges170 bronze badges asked Aug 31, 2018 at 21:39 Huckleberry CarignanHuckleberry Carignan 2,3385 gold badges20 silver badges43 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

The element is most likely being generated dynamically, so you should wait for the element with page.waitForSelector() before attempting to scrape the 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);
发布评论

评论列表(0)

  1. 暂无评论