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

How to Fix Empty Object Returns in Puppeteer's `page.evaluate` with `querySelectorAll`?

Barbara Streisand
Release: 2024-11-18 09:31:02
Original
260 people have browsed it

How to Fix Empty Object Returns in Puppeteer's `page.evaluate` with `querySelectorAll`?

Resolving Empty Object Returns in Puppeteer page.evaluate querySelectorAll

In Puppeteer, attempting to retrieve document elements using the querySelectorAll method through the evaluate function often leads to an array of empty objects. This is a common issue encountered while working with Puppeteer.

To resolve this, it's important to note that the values returned from the evaluate function must be JSON serializable. When evaluating complex elements like the 'title' element in the provided example, the resulting objects contain non-serializable values, such as functions.

The solution lies in extracting the desired information from the elements before returning the JSON-serializable values. In this case, we aim to extract the href values from the elements instead of the entire element objects.

By modifying the evaluate function as seen below, you can successfully retrieve a list of href values:

await this.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 ensures that the returned values are JSON serializable and resolves the issue of empty objects in the result array.

The above is the detailed content of How to Fix Empty Object Returns in Puppeteer's `page.evaluate` 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template