在puppeteer中使用devtool-protocol获取所有样式 [英] Getting all styles with devtool-protocol in puppeteer

查看:213
本文介绍了在puppeteer中使用devtool-protocol获取所有样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取页面上所有节点的所有样式,为此,我想使用

I'm trying to get all styles for all nodes on page and for that i want to use CSS.getMatchedStylesForNode from devtool-protocol, but its only working for one node. If loop through an array of nodes i get a lot of warning in console(code below) and nothing is returned. What i'm doing wrong ?

在控制台中警告:

(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();
})();

  • 木偶版本:0.13.0
  • 平台:窗口10
  • 节点:8.9.3
  • 推荐答案

    使用for循环

    const stylesForNodes = []
    for (id of nodes.nodeIds) {
      stylesForNodes.push(await page._client.send('CSS.getMatchedStylesForNode', {nodeId: id}));
    }
    

    这篇关于在puppeteer中使用devtool-protocol获取所有样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆