美文网首页自动化测试
Selenium截图工具类

Selenium截图工具类

作者: LI木水 | 来源:发表于2018-09-06 17:51 被阅读32次
    public class SeleniumUtil {
        private static Log log = LogUtil.logger(SeleniumUtil.class);
        /**
         * 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 Exception {
            //窗口最大化,截图
            //TODO: 长页面截图不能
            driver.manage().window().maximize();
            File scrFile = ((TakesScreenshot) driver)
                    .getScreenshotAs(OutputType.FILE);
            Point p = element.getLocation();
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            BufferedImage img = ImageIO.read(scrFile);
            BufferedImage dest = img.getSubimage(p.getX(), p.getY(),
                    width, height);
            ImageIO.write(dest, "png", scrFile);
            Thread.sleep(1000);
            if (!StringUtils.endsWithIgnoreCase(path, ".png")) {
                path += ".png";
            }
            FileUtils.copyFile(scrFile, new File(path));
            log.info(String.format("为元素【%s】截图成功,保存位置: %s", element.getTagName(), path));
        }
    }
    

    完整的示例:

    public class SeleniumTest {
    
        public static void main(String[] args) throws Exception {
    
            System.setProperty("webdriver.chrome.driver", "D:/tool/chromedriver.exe");
            WebDriver webDriver = new ChromeDriver();
    
            webDriver.get("https://m.weibo.cn/");
            Thread.sleep(1000);
            SeleniumUtil.screenShotForElement(webDriver, webDriver.findElement(By.cssSelector("html")), "/tmp/test.png");
        }
    }
    

    TODO: 暂时还没找到滚动页面后,对长页面进行截图的方式

    test.png

    相关文章

      网友评论

        本文标题:Selenium截图工具类

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