在puppeteer中使用devtool-protocol获取所有样式

问题描述 投票:0回答:1

我正在尝试为页面上的所有节点获取所有样式,为此我想使用来自CSS.getMatchedStylesForNodedevtool-protocol,但它仅适用于一个节点。如果遍历一个节点数组,我会在控制台(下面的代码)中收到很多警告,并且不会返回任何内容。我做错了什么?

控制台警告:

(node:5724) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 11): Error: Protocol error (CSS.getMatchedStylesForNode): Target closed.

我的代码

'use strict';

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page._client.send('DOM.enable');
    await page._client.send('CSS.enable');
    const doc = await page._client.send('DOM.getDocument');
    const nodes = await page._client.send('DOM.querySelectorAll', {
        nodeId: doc.root.nodeId,
        selector: '*'
    });

    const styleForSingleNode = await page._client.send('CSS.getMatchedStylesForNode', {nodeId: 3});
    const stylesForNodes = nodes.nodeIds.map(async (id) => {
        return await page._client.send('CSS.getMatchedStylesForNode', {nodeId: id});
    });

    console.log(JSON.stringify(stylesForNodes));
    console.log(JSON.stringify(styleForSingleNode));

    await browser.close();
})();
  • Puppeteer版本:0.13.0
  • 平台:窗口10
  • 节点:8.9.3
google-chrome-devtools puppeteer
1个回答
1
投票

用于循环的工作

const stylesForNodes = []
for (id of nodes.nodeIds) {
  stylesForNodes.push(await page._client.send('CSS.getMatchedStylesForNode', {nodeId: id}));
}
© www.soinside.com 2019 - 2024. All rights reserved.