英文:
Puppeteer: How can I pass a text into an evaluate function?
问题
我正在使用Puppeteer,并且想要导入并使用以下函数。
async function getTextExceptChild(page, selector) {
const text = await page.evaluate((sel) => {
const element = document.querySelector(sel);
return element ? element.textContent.trim() : null;
}, selector);
return text;
}
const selector = 'a > strong';
console.log(await getTextExceptChild(timeItem, selector));
但是当我使用它时,我收到一个错误。我不知道为什么。
DOMException: 在'Document'上执行'querySelector'失败:'[object HTMLLIElement]' 不是一个有效的选择器。
我还更改了传递给evaluate()的变量名称,以避免重叠,但没有用。我做错了什么吗?
英文:
I'm using Puppeteer, and I want to import and use the following function.
async function getTextExceptChild(page, selector) {
const text = await page.evaluate((sel) => {
const element = document.querySelector(sel);
return element ? element.textContent.trim() : null;
}, selector);
return text;
}
const selector = 'a > strong';
console.log(await getTextExceptChild(timeItem, selector));
But when I use it, I get an error. I don't know why.
DOMException: Failed to execute 'querySelector' on 'Document': '[object HTMLLIElement]' is not a valid selector.
I've also changed the variable names passed to evaluate() to not overlap, but to no avail.
Am I doing something wrong?
答案1
得分: 0
以下是翻译好的部分:
"你的情况下,你的sel实际上是 [object HTMLLIElement](在提供的代码中我没有看到任何对这种类型的引用)。
不管怎样,你可以尝试首先通过puppeteer初始化元素,如下所示:
async function getTextExceptChild(page, selector) {
const textElement = await page.$(selector); // 如果你不希望元素不存在,可以使用waitForSelector
const text = await page.evaluate((e) => {
return e ? e.textContent.trim() : null;
}, textElement);
return text;
}
```"
<details>
<summary>英文:</summary>
Well, in your case your sel is actually [object HTMLLIElement] (I don't see any reference in provided code to this type).
Anyway, you can try to init element via puppeteer first as
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
async function getTextExceptChild(page, selector) {
const textElement = await page.$(selector); // use waitForSelector if you don't expect that element can not to exist
const text = await page.evaluate((e) => {
return e ? e.textContent.trim() : null;
}, textElement);
return text;
<!-- end snippet -->
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论