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");
}
}
test.pngTODO: 暂时还没找到滚动页面后,对长页面进行截图的方式
网友评论