首页 > web前端 > js教程 > 正文

为什么使用'querySelectorAll”时'page.evaluate”返回空对象?

Patricia Arquette
发布: 2024-11-13 13:50:02
原创
203 人浏览过

Why Does `page.evaluate` Return Empty Objects When Using `querySelectorAll`?

Unexpected Empty Object Array Returned by page.evaluate querySelectorAll

When utilizing Puppeteer's page.evaluate function with querySelectorAll, users may encounter an issue where the returned array contains empty objects.

Cause:

The values returned from the page.evaluate function must be JSON serializable. By default, HTML elements are not JSON serializable without modifications.

Solution:

To resolve this issue, the extracted data from the HTML elements should be modified to a JSON serializable format. For instance, if the desired data is the href values of the elements, the following code snippet can be used:

await this.page.evaluate((sel) => {
    let elements = Array.from(document.querySelectorAll(sel));
    let links = elements.map(element => {
        return element.href;
    });
    return links;
}, sel);
登录后复制

This code extracts the href values from the elements and returns them as an array of strings, which is JSON serializable. By modifying the returned values, the issue of empty objects can be avoided.

以上是为什么使用'querySelectorAll”时'page.evaluate”返回空对象?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板