有三种方法可以做到这一点。
我将立即描述我的最终目标:我希望能够用puppeteer拍摄我的网站截图,并将其直接上传到谷歌云存储(例如,使用云功能(。
然而,如果我没有给出本地存储文件的路径,我在实际上传文件时遇到了一个问题
(async () => {
const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox']});
const page = await browser.newPage();
await page.goto('https://google.com');
const filename = await page.screenshot();
await storage.bucket(bucketName).upload(filename, {
gzip: true,
})
console.log(`${filename} uploaded to ${bucketName}.`);
await browser.close();
})();
我尝试了很多方法,比如对图像进行不同的编码,并将其从缓冲区转换为字符串,但我一直遇到同样的两个错误:
- ;路径";参数的类型必须为字符串。收到Buffer的实例,或
- 参数"path"必须是不包含null字节的字符串或Uint8Array
我很感激能得到的所有帮助:D问候
- 将路径选项添加到
page.screenshot()
以存储的第一种方法本地机器中的屏幕截图,然后将此路径添加到storage.bucket(bucketName).upload()
将此图像上传到谷歌云 - 第二种方法是获得base64编码的屏幕截图图像,然后将其上传到带有特定名称的谷歌云
- 第三种方法是将截图图像作为二进制编码,然后将其上传到带有特定名称的谷歌云
- 第一路
(async () => {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('https://google.com');
await page.screenshot({
path: `/screenshot.png`,
});
const bucket = storage.bucket('bucket_name');
const options = {
destination: 'puppeteer_screenshots/screenshot_XXX.png',
gzip: true,
};
await bucket.upload(`/screenshot.png`, options);
console.log("Created object gs://bucket_name/puppeteer_screenshots/screenshot_XXX.png");
await browser.close();
})();
- 第二种方式
(async () => {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('https://google.com');
const screenshotBase64 = await page.screenshot({
encoding: 'base64',
});
const bucket = storage.bucket('bucket_name');
const file = bucket.file('puppeteer_screenshots/screenshot_XXX.png');
await file.save(screenshotBase64, {
metadata: { contentType: 'image/png' },
});
console.log("Created object gs://bucket_name/puppeteer_screenshots/screenshot_XXX.png");
await browser.close();
})();
- 第三种方式
(async () => {
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
const page = await browser.newPage();
await page.goto('https://google.com');
const screenshotBinary = await page.screenshot({ encoding: 'binary' });
const bucket = storage.bucket('bucket_name');
const file = bucket.file('puppeteer_screenshots/screenshot_XXX.png');
await file.save(screenshotBinary, {
metadata: { contentType: 'image/png' },
});
console.log("Created object gs://bucket_name/puppeteer_screenshots/screenshot_XXX.png");
await browser.close();
})();
参考
- 木偶师屏幕截图
- 谷歌云存储(.upload(
- 谷歌云存储(.save(