2017-04-13 57 views
-1

我正在學習selenium Webdriver。我試圖在Chrome瀏覽器上截取屏幕截圖,但我在下面的代碼中遇到了異常(注意:同一段代碼在Firefox上可用)。請幫助我在Chrome上截取屏幕截圖,並請有人解釋爲什麼下面的代碼不適用於Chrome。在Chrome瀏覽器中使用selenium webdriver截圖

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); 
    } 
}  
+1

你有什麼異常? – Thomas

+0

打印您的堆棧跟蹤並確保yoiur chromedriver存在於該位置。 – kushal

回答

2
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();} 
    } 

使用

String screenpath = captureScreenshot(driver, "ScreenshotName") 

記得更改文件的目標在方法調用它。

相關問題