使用Selenium拍摄屏幕截图

问题描述:

我从另一个软件包中导入了此类,并尝试调用此方法,但它不起作用。使用Selenium拍摄屏幕截图

当我在同一个类中创建此方法并调用它时,它正在工作。

private void getScreenshot() throws IOException 
{ 
     File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
     SimpleDateFormat dateFormat = new SimpleDateFormat("DD-MM-YYYY/hh-mm-ssaa"); 
     String destfile = dateFormat.format(new Date()) + ".png"; 
     FileUtils.copyFile(scrFile, new File("D:\\workspace\\Firewall\\Resources\\ScreenShots\\"+destfile)); 
} 
+1

尝试添加一些格式到您的问题,因为它很难读取您的代码。如果有任何 – Andersson

+4

也添加异常日志如果你在另一个类中有这个确切的方法,它不工作,因为它是'私人'。如果是这样的话,你应该把它改为'public'。 – Tom

我想主要的原因是你导入了错误的库。退房:

import java.io.File; 
import java.io.IOException; 
import org.apache.commons.io.FileUtils; 
import org.junit.Test; 
import org.openqa.selenium.OutputType; 
import org.openqa.selenium.TakesScreenshot; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 

而在情况下,如果你的图书馆将是相同的,尝试使用我的方法:

public class TakeScreenshot { 
    WebDriver driver; 
    public TakeScreenshot(WebDriver driver){ 
     this.driver = driver; 
    } 
public void ScreenShot(String nameTc) 
{ 
// Take screenshot and store as a file format 
File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
try { 
// now copy the screenshot to desired location using copyFile //method 
FileUtils.copyFile(src, new File("bin/" + nameTc + ".png")); 
} 
catch (IOException e) 
{ 
    System.out.println(e.getMessage()); 
}} } 

利用这一点,你可以捕捉屏幕截图,只需要调用captureScreenShot()通过发送文件路径进行屏幕截图的方法

public static void captureScreenShot(String filePath) 
    { 
    File scrFile =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 
    try 
    { 
     FileUtils.copyFile(scrFile, new File(filePath)); } 
    catch (IOException e) 
    { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); }}