Puppeteer 查询选择器 - 如何获得第二个匹配项

Puppeteer Query Selectors - how to get second match

<table><tr><td>firstContent</td><td>secondContent</td></tr></table>

用木偶操作者的 page.$eval 查询这个 table 我检索 firstContent。我将如何检索 secondContent

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

您可以这样使用 :nth-child

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

对于更复杂的表达式,您还可以使用 page.evaluate 中的 document.querySelectorAll 函数,然后像这样选择第二个元素:

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 运行 document.querySelectorAll 和 returns 所有匹配元素的数组。

检索第二个元素的示例是:

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