首頁 > 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
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板