我正在尝试获取页面上所有节点的所有样式,为此我想从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();
})();
- Puppeteer版本:0.13.0
- 平台:窗口10
- 节点:8.9.3
使用of loop
工作const stylesForNodes = []
for (id of nodes.nodeIds) {
stylesForNodes.push(await page._client.send('CSS.getMatchedStylesForNode', {nodeId: id}));
}