selenium 窗口截图以及元素截图

(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;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 元素的定位 滑动 1.首先获取整个屏幕的宽度和高度 •intwidth=driver.manage().windo...
    丛鹏阅读 488评论 0 0
  • 1.contexts contexts(self): Returns the contexts within th...
    七月尾巴_葵花阅读 2,167评论 0 10
  • 梦里 反反复复地回到那个地方 苏醒 永不褪去却是最初的感动 她 是阿酒一生的记忆来铭记 ——题记 花丛,蝴蝶,...
    moe阿酒阅读 251评论 0 0
  • 1.上学(跑操) 2.晨诵诗歌:小小的日记本 3.第一节课 4.第二节课 5.舞蹈队 6.数学课:做练习册 7.体...
    彤心无穷阅读 170评论 2 2
  • 酵素是通过清理肠道血液淋巴内脏毒素的一种排毒养生方法。酵素本身就是体内的每一种有活性的充当人体生化反应催化作用的...
    狒狒i乄阅读 350评论 0 0