>>分享Java编程技术,对《Java面向对象编程》等书籍提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 22638 个阅读者 刷新本主题
 * 贴子主题:  Java版Selenium 截取网页上特定元素的图片的方法 回复文章 点赞(0)  收藏  
作者:sunshine    发表时间:2020-01-09 12:02:11     消息  查看  搜索  好友  邮件  复制  引用

需要引入的包
import java.io.*;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.*;
import java.util.*;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.nio.file.*;
import java.nio.file.attribute.*;
import javax.imageio.ImageIO;

具体的方法

/**
     * This method for screen shot element
     *
     * @param driver
     * @param element
     * @param path
     * @throws InterruptedException
     */

    public static void screenShotForElement(WebDriver driver,
            WebElement element, String path) throws InterruptedException {
        //先截取整个网页的图片,存放在scrFile文件中
        File scrFile = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        try {
            //获得特定元素在整个网页图片中所在的位置和区域大小
            Point p = element.getLocation();
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            Rectangle rect = new Rectangle(width, height);
            BufferedImage img = ImageIO.read(scrFile);
            BufferedImage dest = img.getSubimage(p.getX(), p.getY(),
                    rect.width, rect.height);
            //截取特定元素所在区域的图片,把图片保存到scrFile文件中
            ImageIO.write(dest, "png", scrFile);
            Thread.sleep(1000);
            //利用Apache Common包中的FileUtils类进行文件拷贝
            FileUtils.copyFile(scrFile, new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

此方法的不足之处是,对整个网页的截屏取决于显示器屏幕的大小,对于超出屏幕的网页区域不能截屏。如果尝试对不在屏幕显示范围内的特定元素进行截取子图片,会抛出outside of Raster异常。

关于抓取网页图片的其他实用方法,请参考 盘点用Java抓取HTTP服务器和FTP服务器的网页数据或图片等数据的实用技巧
————————————————
原文链接:https://blog.csdn.net/unhappycode/article/details/50316073


程序猿的技术大观园:www.javathinker.net

[这个贴子最后由 flybird 在 2020-01-10 16:16:32 重新编辑]
网站系统异常


系统异常信息
Request URL: http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=1257

java.lang.NullPointerException

如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员