java - Selenium / Java - 获取整页截图
问题描述
开箱即用,webdriver 只截取可见页面区域的屏幕截图。继这篇文章之后,我想问一下当页面长度大于视口时,如何使用 Java 在 Selenium 中截取整页截图?
描述如何做到这一点的帖子要么没有答案(例如这个),要么指向提供功能的AShot库(例如这个),但它有一些问题,这意味着我不想使用它。具体来说,当在例如 Browserstack 上使用远程驱动程序时,它只呈现屏幕截图的左半部分。此外,它不再由原作者维护,因此为本质上相当简单的问题编写一个新函数似乎更合适。
解决方案
先决条件:访问WebDriver
. 我的是用代码所在的类实例化的。
协调截图大小和页面向下滚动的主要函数如下。请注意,图像格式是为了使其与pdiff兼容:
public void takeFullScreenshot(String outputFile) throws IOException {
JavascriptExecutor js = ((JavascriptExecutor) webDriver);
// Scroll right to the top
js.executeScript("window.scrollTo(0,0)");
// Get the height of the screen
int windowHeight = ((Number) js.executeScript("return window.innerHeight")).intValue();
// Get the total height of the page
int pageHeight = ((Number) js.executeScript("return document.body.scrollHeight")).intValue();
// Calculate the number of full screen shots
double fullFraction = pageHeight / windowHeight;
int fullShots = (int) fullFraction; // this simply removes the decimals
// Initialise ouput image
int imageWidth = webDriver.manage().window().getSize().width;
BufferedImage fullScreenshot = new BufferedImage(imageWidth, pageHeight, BufferedImage.TYPE_4BYTE_ABGR);
// Get the graphics
Graphics2D fullGraphics = fullScreenshot.createGraphics();
// Calculate our scroll script
String script = "window.scrollBy(0," + String.valueOf(windowHeight) + ")";
// Loop - for the required number of full screenshots
for (int aShot = 0; aShot < fullShots; aShot ++) {
// Sort out the screenshot and paste it in the correct place
pasteScreenshot(fullGraphics, aShot * windowHeight);
// scroll
js.executeScript(script);
}
// Final phase - scroll to the bottom
js.executeScript(script); // we know this goes too far down, but should be OK.
// Take final screenshot and paste at the bottom
pasteScreenshot(fullGraphics, pageHeight - windowHeight);
// Save the whole thing to output file.
ImageIO.write(fullScreenshot, "PNG", new File(outputFile));
}
将截图粘贴到输出图形正确位置的小函数如下:
private void pasteScreenshot (Graphics2D outputGraphics, int yCoordinate) throws IOException {
// Take screenshot and hold it as an image
File tmpFile = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
BufferedImage tmpImage = ImageIO.read(tmpFile);
// Draw it on the graphics of the final output image
outputGraphics.drawImage(tmpImage, null, 0, yCoordinate);
}
希望这是有用的。
推荐阅读
- c# - 由于 AssemblyResolve 事件,打开 DataSet Visualizer 时出现异常
- ios - UIPrinterPickerController 未在 iOS 13 上显示
- mysql - 在 ELT 中使用动态列表
- r - 如何在 R 中以 2 y 轴平滑我的线?
- python - 3.8.1 数据/ETL 工作流的生产和沙盒环境
- reactjs - 使用带有道具的构造函数的正确方法?
- go - 为什么在新计算机上访问 Firestore 时出现“恐慌:运行时错误:无效的内存地址或零指针取消引用”?
- javascript - Mongoose 查询最近 24 小时内获得点赞的文档
- javascript - Promise.allSettled 中的 promise 数组的顺序以及创建数据库事务的顺序?
- regex - GREP 正则表达式无法正常工作,但我的正则表达式是正确的