【问题标题】:When is an elementHandle not an elementHandle什么时候 elementHandle 不是 elementHandle
【发布时间】:2020-01-23 01:26:24
【问题描述】:

在 puppeteer api 文档中定义了一个 ElementHandle:

ElementHandle represents an in-page DOM element. ElementHandles can be created with the page.$ method.

因此,给定一个 ElementHandle,我应该能够执行您可以对页面执行的所有基本功能:.click、.$$、.$x、.hover 等

同一个文档定义 page.$x(expression)

expression <string> expression to evaluate (Xpath Expression)
returns: <Promise<Array<ElementHandle>>>

所以我有以下返回 ElementHandles 数组:

const cameraRowList = await page.$x("//div[contains(@class, 'camera-row')]");

我实际上按预期在数组中获得了 5 个项目。所以我需要遍历这个列表并检查 ElementHandles 是否有 id='locationChecked' 的 svg 对象。如果是,请单击它。 (目前除了第 4 个之外,其他所有人都有这个 id)

for (const cameraRow of cameraRowList) {
   const [cameraHasLocation] = await cameraRow.$x("//div[@class='hasLocation']//*[@id='locationChecked']");
   if (cameraHasLocation) {
      const [cameraSelectBox] = await cameraRow.$x("//div[contains(@class, 'checkbox')]");
      await cameraSelectBox.click();
   }
}

问题有两个方面。

首先:当它遍历 Array 中的 5 个 ElementHandles 时,它总是会找到/评估“locationChecked”对象,即使在 4 日它不存在时也是如此。

第二:当它执行cameraSelectionBox.click()时;它总是点击第一个。

这告诉我它可能忽略了 ElementHandle 的范围,而是使用了整个页面。然后在它为数组的每个通道找到的第一个执行。

如何确保范围保持在所使用的 ElementHandle 范围内?

【问题讨论】:

  • 您是否尝试在浏览器上使用document.evaluate 并查看您得到的结果。这就是 $x 正在使用的东西。
  • 在 chrome 控制台中?不确定要使用的语法。我从未使用过 document.evaluate。
  • 你有一些公共的 HTML 可以玩吗?
  • 我没有。我能够使语法正常工作。 document.evaluate("//div[@class='statsRow']//div[@class='hasLocationIcon']//*[@id='locationChecked']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null) .singleNodeValue;确实返回列表中的第一项
  • 如果将第二个cameraRow 作为第三个参数传递会发生什么?你得到第二行的 locationChecked 了吗?

标签: javascript puppeteer jest-puppeteer


【解决方案1】:

我想通了。问题出在我的 xpath 上。

const [cameraHasLocation] = await cameraRow.$x("//div[@class='hasLocation']//*[@id='locationChecked']");

我应该将搜索设为相对“./”,我使用的是忽略 elementHandle 范围的全局“//”:

const [cameraHasLocation] = await cameraRow.$x("./div[@class='hasLocation']//*[@id='locationChecked']");

【讨论】:

    猜你喜欢
    • 2020-08-05
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多