【发布时间】:2017-09-06 23:55:26
【问题描述】:
我有一个用例需要使用 Headless Chrome Network (https://chromedevtools.github.io/devtools-protocol/tot/Network/) 来拦截所有图片请求,并在保存之前找出图片大小(基本丢弃图标等小图片)。
但是,我无法找到一种在保存之前将图像数据加载到内存中的方法。我需要将它加载到 Img 对象中以获取 width 和 height。 Network.getResponseBody 正在使用我在 Network.requestIntercepted 中无权访问的 requestId。另外Network.loadingFinished 总是在encodedDataLength 变量中给我“0”。我不知道为什么。所以我的问题是:
如何拦截所有来自jpg/png请求的响应并获取图片数据?无需通过 URL 字符串将文件保存到磁盘并重新加载。
最佳:如何从标题响应中获取图像尺寸?那我就完全不用把数据读入内存了。
我的代码如下:
const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');
const file = require('fs');
(async function() {
async function launchChrome() {
return await chromeLauncher.launch({
chromeFlags: [
'--disable-gpu',
'--headless'
]
});
}
const chrome = await launchChrome();
const protocol = await CDP({
port: chrome.port
});
const {
DOM,
Network,
Page,
Emulation,
Runtime
} = protocol;
await Promise.all([Network.enable(), Page.enable(), Runtime.enable(), DOM.enable()]);
await Network.setRequestInterceptionEnabled({enabled: true});
Network.requestIntercepted(({interceptionId, request, resourceType}) => {
if ((request.url.indexOf('.jpg') >= 0) || (request.url.indexOf('.png') >= 0)) {
console.log(JSON.stringify(request));
console.log(resourceType);
if (request.url.indexOf("/unspecified.jpg") >= 0) {
console.log("FOUND unspecified.jpg");
console.log(JSON.stringify(interceptionId));
// console.log(JSON.stringify(Network.getResponseBody(interceptionId)));
}
}
Network.continueInterceptedRequest({interceptionId});
});
Network.loadingFinished(({requestId, timestamp, encodedDataLength}) => {
console.log(requestId);
console.log(timestamp);
console.log(encodedDataLength);
});
Page.navigate({
url: 'https://www.yahoo.com/'
});
Page.loadEventFired(async() => {
protocol.close();
chrome.kill();
});
})();
【问题讨论】:
-
我的理解是API目前不允许做这样的事情。投票结束。
标签: node.js google-chrome headless-browser google-chrome-headless