java 在 Chrome 浏览器的 selenium webdriver 中截取屏幕截图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43386398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Taking screenshot in selenium webdriver in Chrome browser
提问by ashish singh
I am learning selenium Webdriver. I was trying to take screenshot on chrome browser but I got exception for below code (Note: Same piece of code works on firefox). Kindly help me out to take a screenshot on Chrome and please somebody explain me why below code is not working on Chrome.
我正在学习 selenium Webdriver。我试图在 chrome 浏览器上截取屏幕截图,但我得到了以下代码的异常(注意:同一段代码适用于 firefox)。请帮我在 Chrome 上截图,请有人解释为什么下面的代码在 Chrome 上不起作用。
public class ScreenShot
{
public static void main(String[] args) throws IOException
{
String key = "webdriver.chrome.driver";
String value = "./driver/chromedriver.exe";
System.setProperty(key, value);
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.co.in");
TakesScreenshot screen = (TakesScreenshot) driver;
File srcFile = screen.getScreenshotAs(OutputType.FILE);
File destFile = new File("d:/google.png");
FileUtils.copyFile(srcFile, destFile);
}
}
回答by Jordan Benyon
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public static String captureScreenshot (WebDriver driver, String screenshotName){
try {
TakesScreenshot ts = (TakesScreenshot)driver;
File source = ts.getScreenshotAs(OutputType.FILE);
String dest = "/Users/CD6255ABQA/Desktop/Debug Images/" + screenshotName + ".png";
File destination = new File(dest);
FileUtils.copyFile(source, destination);
return dest;
}
catch (IOException e) {return e.getMessage();}
}
Call it using
调用它使用
String screenpath = captureScreenshot(driver, "ScreenshotName")
Remember to change the file destination in the method.
请记住在方法中更改文件目标。