【问题标题】:How to select a block with Puppeteer如何使用 Puppeteer 选择块
【发布时间】:2018-03-12 04:17:14
【问题描述】:

我正在尝试从 Puppeteer 获取块列表的高度,但我无法在 page.evaluate() 中选择我的块,因为它会引发错误。

所以,我有这个代码:

(async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(`data:text/html,${html}`);

        for (let property in blockIds) {
            if (blockIds.hasOwnProperty(property)) { console.log(property);
                const height = await page.evaluate(property, () => {
                    return document.getElementById(property).offsetHeight;
                });
                console.log(property, height)
            }
        }

        await browser.close();
    })();
  • html 是字符串中的有效 HTML 页面。
  • blockIds 是这种类型的对象:{ 'block-id': null, 'block-id-2': null}

我的想法是获取所有块的高度,这样我就可以得到以下输出: {'block-id': 123, 'block-id-2': 321}

但是当我运行这段代码时,我得到了以下输出 (注意 question-2 是我的 blockId)

问题2

(节点:6338)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):错误:评估失败:ReferenceError:未定义问题 在:1:1

(node:6338) [DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

我真的不明白为什么这段代码不起作用,因为如果我直接在 document.getElementById 中输入 «question-2»,Puppeteer 会返回正确的高度。

那么,我错过了什么?

【问题讨论】:

    标签: javascript html node.js puppeteer


    【解决方案1】:
    1. 该函数应作为 page.evaluate 的第一个参数传递,如 Puppeteer 的文档中所述。

    https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args

    1. 传递给page.evaluate 的任何参数也必须传递给您要传递的函数。 page.evaluate((arg)=>{}, arg);

    2. 对于for...in 循环,值未分配给property,它正在分配属性名称。要访问 for...in 循环中的值,您应该执行以下操作:blockIds[property]

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

    把它们放在一起你会得到:

    await page.evaluate((property) => {
        return document.getElementById(property)_.offsetHeight;
    }, blockIds[property])
    

    您可能需要考虑从for...in 循环切换到for...of 循环。这会将值分配给property,从而让您获得更简洁的循环体,因为它还会忽略从原型继承的属性,因此您可以省略.hasOwnProperty 检查,因为它不需要。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

    这将导致:

    for (let property of blockIds) {
        //no need to check for .hasOwnProperty here
        const height = await page.evaluate((property) => {
            return document.getElementById(property).offsetHeight;
        }, property); //no need to use blockIds[property] here
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 2020-09-03
      • 1970-01-01
      • 2018-01-29
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      相关资源
      最近更新 更多