一、TakeScreenshout
本篇介绍Selenium中截图类TakeScreenshout,这个类主要是获取浏览器窗体内的内容,不包括浏览器的菜单和桌面的任务栏区域。
package lessons; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class TakeScreenshot { public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", ".\Tools\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.baidu.com"); Thread.sleep(1000); // 调用截图方法 File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { // 拷贝截图文件到我们项目./Screenshots FileUtils.copyFile(src, new File(".\Screenshots\screen.png")); } catch (IOException e) { System.out.println(e.getMessage()); } } }
二、Robot类
前面我们介绍了Selenium中TakeScreenshot类来截图,得到的图片是浏览器窗口内的截图。有时候,只截浏览器窗口内的图是不够的,而且TakeScreenshot截图只针对浏览器的web事件。
package lessons; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class TakeScreenshot { public static void main(String[] args) throws Exception { System.setProperty("webdriver.chrome.driver", ".\Tools\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.baidu.com"); Thread.sleep(1000); // 调用截图方法 BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); try{ ImageIO.write(image, "png", new File(".\Screenshots\screen_robot.png")); }catch(IOException e){ System.out.println(e.getMessage()); } } }