【发布时间】:2019-04-28 05:50:56
【问题描述】:
我尝试从多个页面截取屏幕截图,这些页面应该完全加载(包括延迟加载的图像)以供以后比较。
我发现lazyimages_without_scroll_events.js example 很有帮助。
使用以下代码,屏幕截图看起来不错,但存在一些主要问题。
async function takeScreenshot(browser, viewport, route) {
return browser.newPage().then(async (page) => {
const fileName = `${viewport.directory}/${getFilename(route)}`;
await page.setViewport({
width: viewport.width,
height: 500,
});
await page.goto(
`${config.server.master}${route}.html`,
{
waitUntil: 'networkidle0',
}
);
await page.evaluate(() => {
/* global document,requestAnimationFrame */
let lastScrollTop = document.scrollingElement.scrollTop;
// Scroll to bottom of page until we can't scroll anymore.
const scroll = () => {
document.scrollingElement.scrollTop += 100;
if (document.scrollingElement.scrollTop !== lastScrollTop) {
lastScrollTop = document.scrollingElement.scrollTop;
requestAnimationFrame(scroll);
}
};
scroll();
});
await page.waitFor(5000);
await page.screenshot({
path: `screenshots/master/${fileName}.png`,
fullPage: true,
});
await page.close();
console.log(`Viewport "${viewport.name}", Route "${route}"`);
});
}
问题:即使page.waitFor() 的值更高(超时),有时页面上与前端相关的所有 JavaScript 都没有完全执行。
对于一些旧页面,一些 JavaScript 可能会更改前端。 F.e.在一个遗留案例中是jQuery.matchHeight。
最佳情况:在理想情况下,Puppeteer 会等到所有 JavaScript 都被评估和执行。 这样的事情可能吗?
编辑
在cody-g 的帮助下,我可以稍微改进一下脚本。
function jQueryMatchHeightIsProcessed() {
return Array.from($('.match-height')).every((element) => {
return element.style.height !== '';
});
}
// Within takeScreenshot() after page.waitFor()
await page.waitForFunction(jQueryMatchHeightIsProcessed, {timeout: 0});
...但它远非完美。看来我必须为不同的前端脚本找到类似的解决方案才能真正考虑目标页面上发生的一切。
在我的例子中,jQuery.matchHeight 的主要问题是它在不同的运行中处理不同的高度。可能是由于图像延迟加载引起的。看来我必须等到可以用 Flexbox 替换它。 (^_^)°
其他需要解决的问题:
禁用动画:
await page.addStyleTag({
content: `
* {
transition: none !important;
animation: none !important;
}
`,
});
处理幻灯片:
function handleSwiperSlideshows() {
Array.from($('.swiper-container')).forEach((element) => {
if (typeof element.swiper !== 'undefined') {
if (element.swiper.autoplaying) {
element.swiper.stopAutoplay();
element.swiper.slideTo(0);
}
}
});
}
// Within takeScreenshot() after page.waitFor()
await page.evaluate(handleSwiperSlideshows);
但还是不够。我认为对这些遗留页面进行可视化测试是不可能的。
【问题讨论】:
-
你有没有找到一个通用的方法来完成这个?
-
遗憾的是没有。我所做的一切都在我的 EDIT 中提及。
标签: javascript node.js google-chrome testing puppeteer