Home > Web Front-end > JS Tutorial > body text

Why does Puppeteer's `page.evaluate` return empty objects with `querySelectorAll`?

DDD
Release: 2024-11-22 06:49:17
Original
644 people have browsed it

Why does Puppeteer's `page.evaluate` return empty objects with `querySelectorAll`?

Puppeteer Evaluated QuerySelectorAll Returning Empty Objects

When using Puppeteer's page.evaluate function to query page elements with querySelectorAll, you may encounter an issue where the returned array contains empty objects. This occurs because JavaScript objects are not inherently JSON-serializable.

One potential solution is to extract specific data from the elements, ensuring it can be serialized into JSON. For instance, if you're interested in the href attribute of elements, you can modify your code as follows:

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

This code will return an array of strings representing the href attributes of the selected elements, which can be easily serialized and printed.

The above is the detailed content of Why does Puppeteer's `page.evaluate` return empty objects with `querySelectorAll`?. 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