首页 > 解决方案 > Puppeteer 选择表格单元格的第 n 个子项中的链接

问题描述

我有一个功能:

const tableData = await page.evaluate(() => {
 const tds = Array.from(document.querySelectorAll('table tbody tr td'))
 for (var i = 0; i < tds.length; i++) {
 ...
 ...
  availableDates.push([i,dateString,day])
 }
 return availableDates
}

这个函数循环一个表格的所有单元格,我根据一些条件过滤一些日期。

到现在为止还挺好。单元格包含我要单击的 href。该数组包含我要单击第一个数组项的单元格的编号,因此我尝试了:

await page.focus('table tbody tr td:nth-child('+tableData[0][0]+') a' )
    await page.keyboard.type('\n');

但没有运气。我收到以下错误消息:

(node:81325) UnhandledPromiseRejectionWarning: Error: No node found for selector: table tbody tr td:nth-child(109) a
.......

我必须改变什么?谢谢。

标签: javascriptnode.jspuppeteer

解决方案


这不是 CSS 选择器的工作方式。您不能做也不能td:nth-child(109)期望选择不同表格行中的元素。我会尝试使用.click(),通过page.clickpage.evaluate(() => element.click);

打字\n似乎是一个错误的方向,明确地调用点击——这是我的建议。

用于page.clickhttps ://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageclickselector-options

当谈到实际找到正确的单元格时,我会在更高范围内使用辅助数组(闭包),在那里添加所有内容(一维数组),然后您可以通过数字引用它们,例如您尝试使用nth-child方法。


推荐阅读