【问题标题】:How to iterate over a table and then hover on a particular row having a given column value in puppeteer?如何遍历表,然后将鼠标悬停在 puppeteer 中具有给定列值的特定行上?
【发布时间】:2021-04-05 22:37:08
【问题描述】:

该表的列如下所示:

| 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 实现这一点?

【问题讨论】:

    标签: testing integration-testing puppeteer ui-automation


    【解决方案1】:

    您可以在特定列上使用nth-childs(如果列号已知,如您的示例所示),它可以在表的行上进行迭代,如下所示:

    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.hoverpage.click 可用于第三列的tds 以实现用户删除。这部分代码取决于实际页面的行为。

    【讨论】:

    • 嘿@theDavidBarton!这条线 const currentUserString = await page.$eval(currentUser, el =&gt; el.innerText) 是给 Evaluation failed: ReferenceError: cov_218kt0db29 is not defined ,你知道为什么吗?
    • (1) 如果您将 Jest(或任何其他依赖于伊斯坦布尔的测试库)与 puppeteer 一起使用,则有时会出现此问题,这里有一些解决方法的建议:stackoverflow.com/questions/55272295/…; (2) 如果您尝试传递$eval 范围之外的变量,则应将其作为参数传递:stackoverflow.com/questions/50657830/…(但如果您遵循我上面的建议,则不太可能是问题的原因)。希望对您有所帮助。
    • 谢谢@theDavidBarton!我明白了!
    猜你喜欢
    • 2021-12-24
    • 2016-08-08
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多