【发布时间】:2015-07-22 12:18:16
【问题描述】:
我使用 html2canvas.js 库与 selenium 一起拍摄全页屏幕截图。
public class ChromeCanvasCapture {
private static final String APP_URL = "http://www.flipkart.com";
public static String getFileContent(String filePath)
throws FileNotFoundException, IOException {
FileInputStream inputStream = new FileInputStream(filePath);
String fileContent = IOUtils.toString(inputStream);
inputStream.close();
return fileContent;
}
public static void main(String[] args) {
WebDriver webDriver = null;
try {
System.setProperty("webdriver.chrome.driver",
"D:\\Drivers\\chromedriver.exe");
webDriver = new ChromeDriver();
webDriver.get(APP_URL);
webDriver.manage().window().maximize();
if (webDriver instanceof JavascriptExecutor) {
// scroll to the bottom of the page
((JavascriptExecutor) webDriver) .executeScript("window.scrollTo(0,document.body.scrollHeight)");
// //scroll to the top of the page
((JavascriptExecutor) webDriver)
.executeScript("window.scrollTo(0,0)");
}
String jsFile = getFileContent("html2canvas.js");
jsFile = jsFile
+ " var webDriverCallback = arguments[arguments.length - 1]; html2canvas(document.body, {onrendered: function(canvas) {var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');; webDriverCallback(img); }";
System.out.println(jsFile);
webDriver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);
if (webDriver instanceof JavascriptExecutor) {
JavascriptExecutor executor = (JavascriptExecutor) webDriver;
Object result = executor.executeAsyncScript(jsFile);
String imageString = String.valueOf(result);
byte[] imageData = Base64.decodeBase64(imageString);
OutputStream outputStream = new FileOutputStream(
"C:\\Captures\\canvas_captured.png");
outputStream.write(imageData);
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// webDriver.quit();
}
}
}
我将 html2canvas.js 文件保存在我的 java 项目的类路径中。我用来截屏的java脚本代码是:
var webDriverCallback = arguments[arguments.length - 1];
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL('image/png').replace('data:image/png;base64,', '');;
webDriverCallback(img);
}
});
我能够捕捉到 Flipkart 页面的全页屏幕截图,但其中没有任何图像。
我无法使用 Chrome 中的 TakeScreenshot 实用程序,因为它不允许使用 chrome 浏览器拍摄全页屏幕截图。
【问题讨论】:
标签: java google-chrome selenium selenium-webdriver html2canvas