[英]Puppeteer: Lazy images not loading in headless mode
这是我的代码。 我正在使用AdBlock
Plus 扩展。
我的任务是截取 web 页面(已使用延迟加载)的屏幕截图,其中右侧栏中的图像位于PAID CONTENT
标题下,图像位于底部PAID CONTENT
标题下。
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
const pathToExtension = require('path').join(__dirname, 'abp_chrome');
const browser = await puppeteer.launch({
headless: true,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`
]
});
const page = await browser.newPage();
await timeout(5000);
await page.setViewport({width: 1200, height: 1200});
await page.goto('https://edition.cnn.com/2015/07/31/world/mh370-debris-
investigation/index.html', {waitUntil: 'load', timeout: 0});
await page.evaluate(() => {
window.getDimensions = function(element) {
rect = element.getBoundingClientRect();
return {
x: rect.x,
y: rect.y,
width: rect.width,
height: rect.height
};
};
});
await autoScroll(page);
await page.screenshot({path: 'example.png', fullPage: true});
await browser.close();
})();
async function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function autoScroll(page){
await page.evaluate(async () => {
await new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
resolve();
}
}, 500);
});
});
}
我使用滚动来加载延迟图像,但图像没有像我在屏幕截图中看到的那样加载。
async function autoScroll(page){
let criteria=3; //lazy load 3 page
for (let pageIndex = 1; pageIndex < criteria; pageIndex++) {
await page.evaluate(async () => {
let x = await document.querySelectorAll(
'set lazy element selector array'
);
await x[x.length - 1].scrollIntoView();
return x.length;
});
await page.waitFor(1000);
}
}
2022 答案:
如果新的 headless 选项在 headful 而不是 headless 下工作,则可以解决这个问题。 来自 Github 的讨论:“ headless: 'chrome'
意味着与 headful 模式相同的浏览器实现。旧的 headless 模式实际上是一个不同的浏览器。” 设置为headless: 'chrome'
亲自为我解决了这个问题
puppeteer.launch({
headless: 'chrome'
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.