Home  >  Article  >  Web Front-end  >  How to use selenium to take screenshots and generate images

How to use selenium to take screenshots and generate images

一个新手
一个新手Original
2017-09-18 10:03:022665browse

When you need to save images on a web page locally, use web page screenshots.

Because the driver provided by the selenium jar package simulates page operations, there is no right-click attribute. You can save the image to the local area by simulating a right-click of the mouse. Not only are the steps complicated, but also need to introduce other jar packages. Personally, I think there is no need to go to a lot of trouble. Using the selenium jar package TakesScreenshot attribute to take screenshots can also achieve the purpose of generating images.

Operation steps:

##        
 1 获取图片元素,得到图片位置和大小
WebElement imgElement = driver.findElement(By.id("img"));
Point location = webElement.getLocation(); 
//  获得位置。
Dimension size = webElement.getSize(); // 
大小
2 创建全屏截图,通过ImageIo 读取形式
TakesScreenshot takesScreenshot = (TakesScreenshot) driver;
BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(takesScreenshot.getScreenshotAs(OutputType.BYTES)));
3 截取图片,生成BufferedImage
 BufferedImage croppedImage = originalImage.getSubimage( location.getX(), location.getY(), size.getWidth(), size.getHeight());
##
4  本地生成图片
String fileUrl = ""; // 图片路径
File file = new File(fileUrl);
ImageIO.write(croppedImage , "png", file);  // 内容写入

The above is the detailed content of How to use selenium to take screenshots and generate images. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn