我使用过 Nodejs 并尝试截取给定 URL 的屏幕截图。它在本地运行完美,但部署到 Azure 后在创建 puppeteer 时出现问题。
代码
exports.getScreenShot = async function (req, res) {
const requesturl = req.param('url');
if (!requesturl) {
return res.send(400, 'Missing url');
}
const parsedUrl = url.parse(requesturl);
if (!parsedUrl.protocol) {
return res.send(400, 'Invalid url, missing protocol');
}
if (!parsedUrl.hostname) {
return res.send(400, 'Invalid url, missing hostname');
}
const options = {
'width': req.param('width'),
'height': req.param('height'),
'delay': req.param('delay'),
'userAgent': req.param('userAgent'),
'full': (req.param('full') === 'true')
};
options.width = options.width || 1024;
options.height = options.height || 768;
options.delay = options.delay || 200;
const browser = await puppeteer.connect({
browserWSEndpoint: 'wss://chrome.browserless.io/'
});
let page = await browser.newPage();
await page.goto(requesturl);
await page.waitFor(parseInt(options.delay));
let imageName = parsedUrl.hostname.replace(/\W/g, '_');
let pathName = parsedUrl.pathname.replace(/\W/g, '_').replace(/_$/, '');
if (pathName) {
imageName += pathName;
}
imageName = `${imageName}.png`;
var tempPath = temp.path({ suffix: '.png' });
await page.setViewport({ width: parseInt(options.width), height: parseInt(options.height) });
await page.screenshot({
path: tempPath,
fullPage: options.full
});
}