在puppeteer api文档中定义了ElementHandle:
ElementHandle represents an in-page DOM element. ElementHandles can be created with the page.$ method.
因此,有了ElementHandle,我应该能够执行该页面上的所有基本功能:.click,。$$,。$ x,.hover等
同一文档定义页面。$ 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();
}
}
问题是两个方面。
第一:当它遍历数组中的5个ElementHandles时,它始终会查找/评估“ locationChecked”对象,即使在第4位时也不存在。
第二个:当它执行cameraSelectionBox.click();时。它总是单击第一个。
这告诉我,它可能忽略了ElementHandle的范围,而是使用整个页面。然后针对数组的每次遍历在第一个数组上执行。
我该怎么做才能确保范围不超出所使用的ElementHandle范围?
答案 0 :(得分:0)
我知道了。问题出在我的xpath上。
const [cameraHasLocation] = await cameraRow.$x("//div[@class='hasLocation']//*[@id='locationChecked']");
我应该使搜索相对于“ ./”,而我正在使用全局“ //”,而忽略了elementHandle范围:
const [cameraHasLocation] = await cameraRow.$x("./div[@class='hasLocation']//*[@id='locationChecked']");