英文:
Selecting an href element in Puppeteer JS gives invalid error is not a valid selector
问题
我有以下元素:
<a href="javascript:void(0)" class="compareItemsExpand" data-id="5338408">text this link</a>
这在页面上出现多次,我可以这样获取它们:
const hrefs = await page.$$eval(
".title a",
els => els.map(el => el.href)
);
然后,我会像这样循环处理这些元素:
for (const href of hrefs) {
await page.click(href);
}
// href = 'javascript:void(0)'
这会导致以下错误:
DOMException: Failed to execute 'querySelectorAll' on 'Document': 'javascript:void(0)' is not a valid selector.
英文:
I have the following element:
<a href="javascript:void(0)" class="compareItemsExpand" data-id="5338408">text this link</a>
this appears multiple times on the page and I get it like this:
const hrefs = await page.$$eval(
".title a",
els => els.map(el => el.href)
);
I then loop over the elements like so:
for (const href of hrefs) {
await page.click(href);
}
// href = 'javascript:void(0)';
This gives me the error:
DOMException: Failed to execute 'querySelectorAll' on 'Document': 'javascript:void(0)' is not a valid selector.
答案1
得分: 1
这是因为您实际上正在尝试点击javascript:void(0)
,这确实不是正确的选择器。
正确的解决方案是获取元素句柄,然后对它们进行循环操作,
const elementHandles = await page.$$(".title a");
for (const elementHandle of elementHandles) {
await elementHandle.click();
}
英文:
This is because you are actually trying to click javascript:void(0)
which is indeed not the right selector here.
The correct solution would be to get element handles, and then looping over them,
const elementHandles = await page.$$(".title a");
for (const elementHandle of elementHandles) {
await elementHandle.click();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论