美文网首页
selenium 窗口截图以及元素截图

selenium 窗口截图以及元素截图

作者: TungChiu | 来源:发表于2017-12-16 11:39 被阅读0次

    (1) Selenium WebDriver 进行窗口截图

    Selenium WebDriver提供了TakesScreenshot接口来捕捉网页的截屏。这可以在测试执行遇到异常错误的时候将屏幕截取下来,可以知道当时发生了什么。

    package com.example.tests;

    import java.io.File;

    import org.apache.commons.io.FileUtils;

    import org.junit.*;

    import org.openqa.selenium.*;

    import org.openqa.selenium.ie.InternetExplorerDriver;

    public class Screenshot {

        @Test

        public void testTakesScreenshot() {

            WebDriver driver = new InternetExplorerDriver();

            driver.get("http://www.baidu.com");

            try {

                    File srcFile = ((TakesScreenshot)driver).

                    getScreenshotAs(OutputType.FILE);

                    FileUtils.copyFile

                    (srcFile,new File("/User/desktop/screenshot.png"));

            } catch (Exception e) {

                    e.printStackTrace();

        }

        driver.close();

    }

    TakesScreenshot接口提供了getScreenshotAs()方法来捕捉屏幕。上面的列子中指定了OutputType.FILE作为参数传递给getScreenshotAs()方法,告诉它将截取的屏幕以文件形式返回。使用org.apache.commons.io.FileUtils 类中的copyFile()方法来保存getScreenshot()返回的文件对象。TakesScreenshot 接口依赖于浏览器中的API来捕捉屏幕。所以在HtmlUnitDriver中不支持这样使用。OutputType类提供了多种数据型,在前面的例子中我们使用文件它也可以保 类提供了多种数据型,在前面的例子中我们使用文件它也可以保 存为 Base64编码的 字符串,代码如下

    String base64 =((TakesScreenshot)driver).getScreenshotAs(OutputType.BASE64);

    (2)元素截图

    //页面元素截图

    public static File captureElement(WebElement element) throws Exception {

    WrapsDriver wrapsDriver = (WrapsDriver) element;

    // 截图整个页面

    File screen = ((TakesScreenshot) wrapsDriver

    .getWrappedDriver().getScreenshotAs(OutputType.FILE);

    BufferedImage img = ImageIO.read(screen);

    // 获得元素的高度和宽度

    int width = element.getSize().getWidth();

    int height = element.getSize().getHeight();

    // 创建一个矩形使面上面的高度,和宽度

    Rectangle rect = new Rectangle(width, height);

    // 得到元素的坐标

    Point p = element.getLocation();

    BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width,rect.height);

    //存为png格式

    ImageIO.write(dest, "png", screen);

    return screen;

    }

    相关文章

      网友评论

          本文标题:selenium 窗口截图以及元素截图

          本文链接:https://www.haomeiwen.com/subject/rcrswxtx.html