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

javascript - Puppeteer Query Selectors - how to get second match - Stack Overflow

programmeradmin0浏览0评论
<table><tr><td>firstContent</td><td>secondContent</td></tr></table>

Querying this table with puppeteer's page.$eval I retrieve firstContent. How would I retrieve secondContent?

const value = await page.$eval('table tr td', el => { return el.innerHTML });
<table><tr><td>firstContent</td><td>secondContent</td></tr></table>

Querying this table with puppeteer's page.$eval I retrieve firstContent. How would I retrieve secondContent?

const value = await page.$eval('table tr td', el => { return el.innerHTML });
Share Improve this question edited Apr 4, 2019 at 20:19 Thomas Dondorf 25.2k6 gold badges96 silver badges112 bronze badges asked Apr 4, 2019 at 20:00 LokomotywaLokomotywa 2,84411 gold badges47 silver badges80 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 15

You can use :nth-child like this:

const value = await page.$eval('table tr td:nth-child(2)', el => { return el.innerHTML });

For more complex expressions, you could also make use of the document.querySelectorAll function within the page.evaluate and then choose the second element like this:

const value = await page.evaluate(
    () => document.querySelectorAll('table tr td')[1].innerHTML
);

page.$eval runs document.querySelector within the page and return the first match to the selector if you want to access other elements matching your selector use page.$$eval which runs document.querySelectorAll and returns an array of all matched elements.

An example case to retrieve the second element would be:

const second_value = await page.$$eval('table tr td', el => el[1].innerHTML);
发布评论

评论列表(0)

  1. 暂无评论