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);
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!