本帖最后由 辣舞辣舞test 于 2019-5-10 11:18 编辑
ImageIO.write无法写入jepg格式的图片,改成png格式,截的图片是空白的。 package com.ctrip.trains;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;import org.apache.commons.io.FileUtils;import org.apache.commons.io.output.ByteArrayOutputStream;import org.openqa.selenium.By;import org.openqa.selenium.OutputType;import org.openqa.selenium.Point;import org.openqa.selenium.TakesScreenshot;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;public class Screenshot { public static void main(String[] args) throws IOException, InterruptedException { //强制类型转换 /* int a=(int)3.5; System.out.println(a); */ System.setProperty("webdriver.chrome.driver", "/Users/yuxiaojun/Downloads/software/Eclipse/eclipse-workspace/se_2018/Files/chromedriver"); WebDriver driver=new ChromeDriver(); //浏览器窗口最大化 driver.manage().window().maximize(); driver.get("https://user.qunar.com/passport/login.jsp"); Thread.sleep(5000); //截图,结果以文件格式保存 /* File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //将截图复制至指定路径 FileUtils.copyFile(f,new File("/Users/yuxiaojun/Downloads/software/Eclipse/eclipse-workspace/se_2018/Files/1.jpeg")); */ WebElement image=driver.findElement(By.id("vcodeImg")); BufferedImage pic=imageElement(driver,image); ImageIO.write(pic, "png", new File("/Users/yuxiaojun/Downloads/software/Eclipse/eclipse-workspace/se_2018/Files/7.png")); } //截图,结果以bytes类型保存在内存中 public static byte[] Screen(WebDriver driver) { return ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES); } public static BufferedImage imageElement(WebDriver driver,WebElement ele) throws IOException { //获取需要截图的元素的位置 Point location=ele.getLocation(); //从内存读取截图 BufferedImage im=ImageIO.read(new ByteArrayInputStream(Screen(driver))); //从截图中获取指定位置的子图片 BufferedImage subim=im.getSubimage(location.getX(), location.getY(), ele.getSize().getWidth(), ele.getSize().getHeight()); return subim; } }
在学课程 Java Selenium3项目实战
|