Puppeteer: 如何将文本传递给 evaluate 函数?

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

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&#39;t see any reference in provided code to this type).

Anyway, you can try to init element via puppeteer first as

&lt;!-- begin snippet: js hide: false console: true babel: false --&gt;

&lt;!-- language: lang-js --&gt;

    async function getTextExceptChild(page, selector) {
        const textElement = await page.$(selector); // use waitForSelector if you don&#39;t expect that element can not to exist
        const text = await page.evaluate((e) =&gt; {
            return e ? e.textContent.trim() : null;
        }, textElement);
        return text;

&lt;!-- end snippet --&gt;



</details>



huangapple
  • 本文由 发表于 2023年7月24日 20:16:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76754420.html
匿名

发表评论

匿名网友

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

确定