Puppeteer-迭代表行和特定行的复选框

问题描述 投票:0回答:1

我有一个表,其中第一列是每一行的复选框,我想选中包含该行特定列中特定文本的行的复选框。

示例

X | Dave | Smith
X | Bill | Jones

Iterate through all rows and then check the box in the first column if the row has "Jones" for the last name column (col 3)

[该站点上有一些很棒的示例,它们从表中抓取数据并仅输出所述数据,但是我希望实际遍历每一行,然后根据所需需求对给定单元格中的元素执行操作。

剪贴示例

const result = await page.$$eval('#example-table tr', rows => {
  return Array.from(rows, row => {
    const columns = row.querySelectorAll('td');
    return Array.from(columns, column => column.innerText);
  });
});

console.log(result[1][2]); // "C2"

上面的示例非常适合只提取2D数组中的数据,但是我希望遍历每一行以查找特定列中的特定文本,然后对col 0中的元素执行单击操作以检查框。

我正在使用Puppeteer,并且是javascript的新手,因此非常感谢别人可能提供的任何指导。

我已经尝试过很多类似的尝试。

const rows = await page.$$eval('table tbody tr', (rows) => {
    const cols = await page.$$eval('table tbody tr td', (cols) => {
        for (let i=0; i<rows.length; i++) {
            for (let j=0; j<cols.length; j++) {
                // if row[i] col[2] == desired text
                // then check box in row[i] col[0]
            }
        }
    })
}

不确定我是否需要cols的第二个for循环(可能比没有更好?),因为我知道我要检查的文本位于哪一列,并且知道该行的第一个col始终是检查对象框。

随着迭代的进行,我还对如何在该表的位置内的元素进行交互(单击,获取文本)感到困惑。

任何帮助将不胜感激。

javascript html-table puppeteer browser-automation web-testing
1个回答
0
投票

最好迭代tr的:

await page.evaluate(() => {
  // find the tr with Jones
  let tr = [...document.querySelectorAll('tr')].find(tr => tr.innerText.match(/Jones/))
  if(tr){
    // find the checkbox and click it
    let cb = tr.querySelector('input[type="checkbox"]')
    if(cb) {
      cb.click()
    }
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.