问题描述
该表具有如下所示的列:
| Organization | Username | Option |
____________________________________________________________________
| Helloworld | username1 | delete icon appear here on hover |
| Stackoverflow | test | delete icon appear here on hover |
| Puppeteer | username2 | delete icon appear here on hover |
____________________________________________________________________
我想遍历表格并将鼠标悬停在选项上以单击用户名值 = test 的列的删除图标。
如何使用 puppeteer 实现这一点?
解决方法
您可以在特定列上使用 nth-child
(如果列号已知,如您的示例中所示),它可以在表的行上迭代,如下所示:
const numberOfRows = await page.$$eval('table > tbody > tr',rows => rows.length)
for (let n = 1; n < numberOfRows + 1; n++) {
const currentUser = `table > tbody > tr:nth-child(${n}) > td:nth-child(2)` // nth row 2nd column
const currentOption = `table > tbody > tr:nth-child(${n}) > td:nth-child(3)` // nth row 3rd column
const currentUserString = await page.$eval(currentUser,el => el.innerText)
if (currentUserString === 'test') {
try {
await page.hover(currentOption)
await page.click(currentOption)
} catch {}
}
}
Page.hover
和 page.click
可用于第 3 列的 td
以实现用户删除。这部分代码取决于实际页面的行为。