gpt4 book ai didi

javascript - Puppeteer:将截获的图像请求的 URL 更改为 base64 图像

转载 作者:行者123 更新时间:2023-12-04 10:09:44 34 4
gpt4 key购买 nike

我需要拦截 .jpg.gif 图像并将它们替换为 base64 图像。base64 图像将在屏幕截图中可见。

下面的代码阻止了原始图像的加载,但是 base64 图像并没有加载到原始图像的位置。

如何将原始图像的 src 替换为 base64 图像?


await page.setRequestInterception(true);

page.on('request', request => {

const resourceUrl = request.url().toLowerCase();
const base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAADwBAMAAACDA6BYAAAAMFBMVEUAAACHh4fExMQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACKW9M+AAAACXBIWXMAAAsTAAALEwEAmpwYAAADM0lEQVR4AezOgQAAAAjAsFK5P2QgbQQbAAAAAAAAAAAAAN7bSlBQUFDw2LXDnLdBGADDgRMYnwB8/0Nurb1XUKVaNg2CtPjHlzjxlEekAaedh5rJz00xK3GkmFmTSJKyH9VlHfD1V81ewuybMLwiSs2iSjjXVgLTG9ASKKc6g6wFMM7VhcAYrtiIH0RL5sDEqXXAMWqHYMhIyawuBDa/bHsfa46QI4VC31kJoJq1+LsIyKa7PLLqpxrOw7jRq4CB8Sw7pqgATN2dFmRxcCmwAYzIAKPehAJdCZRzYLIBeHwC60IgF0wAiz+qbgYILN8JhDcC1YHEnUC1C8B2HzDZ3sBYLUreFqisaucPCXEPkGMA+2lmB2AKkn6ZqHcDni91Re4E0hB8Ngv9ObkLGKSkQ7ul5pVGdudDQtTvDWu7Eag2KAZg6ux3ryQlgNlBSiXvJPeuxfXo35oaLSCDeRvQ0xLn4sW961EL7/R7xd8O2wO0Int/2cRKsi2QaHsCFWDdE5gAHpuGstDtGklts7n5iSeeeOKJJ554Yvfes1z82f3CF4KJin8JtLY70OruQNseKLsD66ZAdtquQF4ltwbmT2DSmBzJmpwBk5/gN9syCZgAGnlciMw6YO6eKt+Lg1aXANP47YtaeAFaKAw6/6jMusWNA4jM4mSEeKHXVep8n2TWQ1LHgTy7cg0gXw5SRzIJWMaJOsd/6wkuWXMgA5jGn8OwT1/qlBvudxV1AH3XE4Y/45zfLEQa29xxPenufcWpAdNJQA7A9GvBOKyIYzjPB4OyicB2AszDlTkEof/kMqx5frPAJbiydMCT7pGyqUC7DmS8CcpmdTPKI3gNaJ9AmQpkabgOlKVAnr3rwLo1sF+5CR6SycDv04wWcWD9VdABKVsKVICsK5k5j0H7AOocoAE8X+qC0y9rmHIrHWxau2X1W7PABmA26thMaxYI+dpu0UcxnJhpviibB/x9w9oAxs2lTrpkFvAPWn42Q12eDJTrL00UjnVRNbvd+v7aKd0sR9rVJd+fAOTl+/KLO7PeUJfe+wD/5/jRHhwTAAAAAAzp33oldmIGAAAAAAAAAAAAAAAAATWgPUYJ011oAAAAAElFTkSuQmCC';

if (request.resourceType() == 'image' && resourceUrl.indexOf('.png') === -1 &&
resourceUrl.indexOf('.svg') === -1 ||
resourceUrl.indexOf('.jpg') !== -1 ||
resourceUrl.indexOf('.jpeg') !== -1 ||
resourceUrl.indexOf('.gif') !== -1) {

request.respond({
status: 200,
contentType: 'image/jpeg',
headers: {
// location: base64Image
// path: base64Image
url: base64Image
},
});

return; // prevent calling continue twice

}

request.continue();

});


最佳答案

问题

request.respond 不能与 base64 响应一起使用。引自 docs :

NOTE Mocking responses for dataURL requests is not supported.

解决方案

相反,您可以先使用需要从 base64 转换为二进制表示形式的缓冲数据来回答:

const base64Data = 'iVBORw0KGgoAAA...'; // ony the base64 data, without "data:image/png;base64,"
const buffer = Buffer.from(base64Data, 'base64');

// ...

request.respond({
status: 200,
contentType: 'image/png',
body: buffer
});

关于javascript - Puppeteer:将截获的图像请求的 URL 更改为 base64 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61390748/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com