截图方法
public static void snapshot(TakesScreenshot drivername, String filename)
{
// this method will take screen shot ,require two parameters ,one is driver name, another is file name String currentPath = System.getProperty("user.dir"); //get current work folder
System.out.println(currentPath);
File scrFile = drivername.getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
try {
System.out.println("save snapshot path is:"+currentPath+"/"+filename);
FileUtils.copyFile(scrFile, new File(currentPath+"\\"+filename));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Can't save screenshot");
e.printStackTrace();
}
finally
{ System.out.println("screen shot finished");
}
}
1.使用selenium打开百度,截图;
2.输入selenium关键字
3.搜索,截图
具体代码如下:
import java.io.File;
import java.io.IOException; import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; public class TestSaveScreen { private WebDriver driver;
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
driver.get("https://www.baidu.com/");
snapshot((TakesScreenshot)driver,"open_baidu.png");
}
@Test
public void test() {
WebElement searchInput= driver.findElement(By.id("kw"));
searchInput.sendKeys("selenium"); WebElement searchButton= driver.findElement(By.id("su"));
searchButton.click();
snapshot((TakesScreenshot)driver,"search_output.png");
} @AfterClass
public void afterClass() {
driver.quit();
} public static void snapshot(TakesScreenshot drivername, String filename)
{
// this method will take screen shot ,require two parameters ,one is driver name, another is file name String currentPath = System.getProperty("user.dir"); //get current work folder
System.out.println(currentPath);
File scrFile = drivername.getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
try {
System.out.println("save snapshot path is:"+currentPath+"/"+filename);
FileUtils.copyFile(scrFile, new File(currentPath+"\\"+filename));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Can't save screenshot");
e.printStackTrace();
}
finally
{ System.out.println("screen shot finished");
}
}
}
截图效果如下: