Selenium Webdriver——实现截图功能
截图方法
1 public static void snapshot(TakesScreenshot drivername, String filename) 2 { 3 // this method will take screen shot ,require two parameters ,one is driver name, another is file name 4 5 String currentPath = System.getProperty("user.dir"); //get current work folder 6 System.out.println(currentPath); 7 File scrFile = drivername.getScreenshotAs(OutputType.FILE); 8 // Now you can do whatever you need to do with it, for example copy somewhere 9 try { 10 System.out.println("save snapshot path is:"+currentPath+"/"+filename); 11 FileUtils.copyFile(scrFile, new File(currentPath+"\\"+filename)); 12 } catch (IOException e) { 13 // TODO Auto-generated catch block 14 System.out.println("Can't save screenshot"); 15 e.printStackTrace(); 16 } 17 finally 18 { 19 20 System.out.println("screen shot finished"); 21 } 22 }
1.使用selenium打开百度,截图;
2.输入selenium关键字
3.搜索,截图
具体代码如下:
1 import java.io.File; 2 import java.io.IOException; 3 4 import org.apache.commons.io.FileUtils; 5 import org.openqa.selenium.By; 6 import org.openqa.selenium.OutputType; 7 import org.openqa.selenium.TakesScreenshot; 8 import org.openqa.selenium.WebDriver; 9 import org.openqa.selenium.WebElement; 10 import org.openqa.selenium.firefox.FirefoxDriver; 11 import org.testng.annotations.AfterClass; 12 import org.testng.annotations.BeforeClass; 13 import org.testng.annotations.Test; 14 15 public class TestSaveScreen { 16 17 private WebDriver driver; 18 @BeforeClass 19 public void beforeClass() { 20 driver = new FirefoxDriver(); 21 driver.get("https://www.baidu.com/"); 22 snapshot((TakesScreenshot)driver,"open_baidu.png"); 23 } 24 @Test 25 public void test() { 26 WebElement searchInput= driver.findElement(By.id("kw")); 27 searchInput.sendKeys("selenium");29 WebElement searchButton= driver.findElement(By.id("su")); 30 searchButton.click(); 31 snapshot((TakesScreenshot)driver,"search_output.png"); 32 } 33 34 @AfterClass 35 public void afterClass() { 36 driver.quit(); 37 } 38 39 public static void snapshot(TakesScreenshot drivername, String filename) 40 { 41 // this method will take screen shot ,require two parameters ,one is driver name, another is file name 42 43 String currentPath = System.getProperty("user.dir"); //get current work folder 44 System.out.println(currentPath); 45 File scrFile = drivername.getScreenshotAs(OutputType.FILE); 46 // Now you can do whatever you need to do with it, for example copy somewhere 47 try { 48 System.out.println("save snapshot path is:"+currentPath+"/"+filename); 49 FileUtils.copyFile(scrFile, new File(currentPath+"\\"+filename)); 50 } catch (IOException e) { 51 // TODO Auto-generated catch block 52 System.out.println("Can't save screenshot"); 53 e.printStackTrace(); 54 } 55 finally 56 { 57 58 System.out.println("screen shot finished"); 59 } 60 } 61 }
截图效果如下: