在 Puppeteer JS 中选择 href 元素会导致无效错误,这不是有效的选择器。

huangapple go评论118阅读模式
英文:

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();
}

huangapple
  • 本文由 发表于 2023年6月8日 04:01:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定