java - 截屏并通过 Selenium WebDriver 和 java 中的 FileUtils 进行复制

标签 java selenium selenium-webdriver webdriver fileutils

当我尝试使用以下代码获取屏幕截图时,它显示错误。

FileUtils.copyFile(source, new File("*./Screenshots/facebook.png"));

error message

但是当我尝试下面的代码时就可以了。

FileHandler.copy(source,new File("*./Screenshots/facebook.png"));

这是为什么?

完整代码如下

package sample.code;
import java.io.File;

import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.annotations.Test;

public class ScreenShot {

  @Test
  public void facebookScreenShot() throws IOException {

    WebDriver driver= new ChromeDriver();
    driver.get("http://www.facebook.com");
    driver.manage().window().maximize();    
    driver.findElement(By.xpath(".//*[@id='u_0_m']")).sendKeys("screenshot");

    TakesScreenshot ts=(TakesScreenshot)driver;

    File source=ts.getScreenshotAs(OutputType.FILE);    
    FileHandler.copy(source,new File("*./Screenshots/facebook.png"));

    driver.quit();
  }
}

最佳答案

通过使用Robot类,您可以进行截图。以下是截图的代码。

import java.awt.AWTException;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;


public class CaptureScreenshot {

    public static void main(String[]args) throws IOException, HeadlessException, AWTException
    {
        // This code will capture screenshot of current screen      
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

        // This will store screenshot on Specific location
        ImageIO.write(image, "png", new File("C:\\Users\\Screenshot\\CurrentScreenshot.png")); 

    }
}

关于java - 截屏并通过 Selenium WebDriver 和 java 中的 FileUtils 进行复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568448/

相关文章:

java - 在一个 session 期间提交多个事务会提高性能吗?

java - 我试图关闭 Webdriver 上的浏览​​器实例,但无法这样做

java - 如何单击主菜单中的子菜单链接

java - 如何在 Selenium webdriver 中选择下拉选项?

python - 如何阻止 Selenium 在执行期间关闭驱动程序?

java - Storm UI 未启动

java - 在android项目中使用maven库

python - 在python中使用beautiful soup和selenium解析html

java - XML 模式在两种不同情况下有两种同名的元素类型

javascript - 当您将 Selenium 与 chromedriver 一起使用时,网站可以检测到吗?