Home > Web Front-end > JS Tutorial > Why Does Puppeteer's `page.evaluate()` With `querySelectorAll` Return Empty Objects?

Why Does Puppeteer's `page.evaluate()` With `querySelectorAll` Return Empty Objects?

DDD
Release: 2024-11-11 18:38:02
Original
871 people have browsed it

Why Does Puppeteer's `page.evaluate()` With `querySelectorAll` Return Empty Objects?

Understanding Puppeteer's page.evaluate() QuerySelectorAll Returns Empty Objects

Puppeteer's page.evaluate() method is a powerful tool for executing JavaScript within the browser, allowing you to interact with elements on the page and retrieve information. However, sometimes you may encounter an issue where the querySelectorAll() method returns an array of empty objects.

This issue stems from the fact that the values returned from the evaluate function must be JSON serializable. Elements and document objects, like those returned by querySelectorAll(), cannot be directly serialized.

Resolving the Issue

To resolve this issue, it is necessary to extract the desired information from the elements and return only JSON serializable data. In the case of a list of links from the page, you can modify the code as follows:

await page.evaluate((sel) => {
    let elements = Array.from(document.querySelectorAll(sel));
    let links = elements.map(element => {
        return element.href
    })
    return links;
}, sel);
Copy after login

This code will extract the href attribute from each element and return an array of strings, which can be JSON serialized.

The above is the detailed content of Why Does Puppeteer's `page.evaluate()` With `querySelectorAll` Return Empty Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template