在AWS Lambda中使用Puppeteer设置cookies时可能会遇到问题,以及自定义字体未被应用的问题。以下是解决这两个问题的示例代码:
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer-core');
exports.handler = async (event) => {
let browser = null;
try {
// 启动Puppeteer
browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
});
// 创建一个新页面
const page = await browser.newPage();
// 设置cookies
await page.setCookie({
name: 'cookieName',
value: 'cookieValue',
domain: 'example.com',
path: '/',
});
// 进行其他操作...
return {
statusCode: 200,
body: 'Success',
};
} catch (error) {
return {
statusCode: 500,
body: 'Error',
};
} finally {
// 关闭浏览器
if (browser !== null) {
await browser.close();
}
}
};
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer-core');
exports.handler = async (event) => {
let browser = null;
try {
// 启动Puppeteer
browser = await puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
});
// 创建一个新页面
const page = await browser.newPage();
// 添加字体配置
await page.setExtraHTTPHeaders({ 'Accept-Language': 'en-US,en;q=0.9' });
await page.evaluateOnNewDocument(() => {
const newFont = new FontFace('CustomFont', 'url(path/to/custom/font.ttf)');
document.fonts.add(newFont);
document.body.style.fontFamily = 'CustomFont';
});
// 进行其他操作...
return {
statusCode: 200,
body: 'Success',
};
} catch (error) {
return {
statusCode: 500,
body: 'Error',
};
} finally {
// 关闭浏览器
if (browser !== null) {
await browser.close();
}
}
};
这些代码示例解决了在AWS Lambda中使用Puppeteer设置cookies时不起作用的问题,并应用了自定义字体。备注:确保替换示例中的实际路径和域名。