您的位置:首页 > 其它

selenium页面元素截图

2016-08-26 12:04 417 查看
http://blog.csdn.net/fgwvip123/article/details/51671279

[java] view
plain copy

 





package com.selenium.api;  

import java.awt.Rectangle;  

import java.awt.image.BufferedImage;  

import java.io.File;  

  

import javax.imageio.ImageIO;  

  

import org.apache.commons.io.FileUtils;  

import org.junit.Test;  

import org.openqa.selenium.By;  

import org.openqa.selenium.OutputType;  

import org.openqa.selenium.Point;  

import org.openqa.selenium.TakesScreenshot;  

import org.openqa.selenium.WebDriver;  

import org.openqa.selenium.WebElement;  

import org.openqa.selenium.firefox.FirefoxDriver;  

import org.openqa.selenium.internal.WrapsDriver;  

  

public class Util {  

  

    //页面元素截图  

    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;  

    }  

      

    @Test  

    public void testCaptureElement(){  

        WebDriver driver=new FirefoxDriver();  

        driver.manage().window().maximize();  

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

        WebElement wb = driver.findElement(By.id("su"));  

        try {  

            FileUtils.copyFile(captureElement(wb), new File("c:\\a.png"));  

        } catch (Exception e) {  

            e.printStackTrace();  

        }  

        driver.quit();  

    }  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: