是否可以使用Selenium WebDriver进行截图?

(注:不含硒遥控器)


当前回答

import java.io.File;
import java.io.IOException;

import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
 * @author Jagdeep Jain
 *
 */
public class ScreenShotMaker {

    // take screen shot on the test failures
    public void takeScreenShot(WebDriver driver, String fileName) {
        File screenShot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));

        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage(), ioe);
        }
    }

}

其他回答

Java

是的,这是可能的。下面以Java为例:

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Java

这里似乎没有-在Java中截取一个特定元素的截图:

public void takeScreenshotElement(WebElement element) throws IOException {
    WrapsDriver wrapsDriver = (WrapsDriver) element;
    File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
    Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
    Point location = element.getLocation();
    BufferedImage bufferedImage = ImageIO.read(screenshot);
    BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
    ImageIO.write(destImage, "png", screenshot);
    File file = new File("//path//to");
    FileUtils.copyFile(screenshot, file);
}

你可以使用Webdriverclass对象创建一个webdriver支持的selenium对象,然后你可以截屏。

你可以在浏览器中截取网页可见部分的截图:

首先导入:

import java.io.File;
import com.google.common.io.Files;

Then

File src=((TakesScreenshot)driver).getScreenShotAs(OutputType.FILE);
Files.copy(src,new File("new path/pic.jpeg"));

另外,在Selenium4之后,你还可以截取webelement的截图:

WebElement element=driver.findElement(By.xpath("xpath 
 here"));
File src=element.getScreenShotAs(OutputType.FILE);
File.copy(src,new File("new path/pic.jpeg"));

Python

您可以使用Python web驱动程序从windows中捕获图像。使用下面的代码哪个页面需要捕获屏幕截图。

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')