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)));Copy after login
3 截取图片,生成BufferedImage BufferedImage croppedImage = originalImage.getSubimage( location.getX(), location.getY(), size.getWidth(), size.getHeight());Copy after login
##4 本地生成图片 String fileUrl = ""; // 图片路径Copy after login
File file = new File(fileUrl); ImageIO.write(croppedImage , "png", file); // 内容写入Copy after loginThe 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!