我试图获取页面上所有节点的所有样式,为此我想使用devtool-protocol中的CSS.getMatchedStylesForNode
,但它只适用于一个节点。如果遍历一个节点数组,我会在控制台(下面的代码)中收到很多警告,并且不会返回任何内容。我做错了什么?
警告:
(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 :(得分:1)
使用for for循环
const stylesForNodes = []
for (id of nodes.nodeIds) {
stylesForNodes.push(await page._client.send('CSS.getMatchedStylesForNode', {nodeId: id}));
}