例: 打开百度首页 ,进行截图
01 |
packagecom.example.tests; |
03 |
importorg.apache.commons.io.FileUtils; |
05 |
importorg.openqa.selenium.*; |
06 |
importorg.openqa.selenium.ie.InternetExplorerDriver; |
07 |
public classSelenium2 { |
09 |
public voidtestTakesScreenshot() { |
10 |
WebDriver driver = newInternetExplorerDriver(); |
11 |
driver.get("http://www.baidu.com"); |
13 |
File srcFile = ((TakesScreenshot)driver). |
14 |
getScreenshotAs(OutputType.FILE); |
16 |
(srcFile,newFile("d:\\screenshot.png")); |
17 |
} catch(Exception e) { |
TakesScreenshot接口提供了getScreenshotAs()方法来捕捉屏幕。上面的例子中,我们指定了OutputType.FILE作为参数传递给getScreenshoAs()方法,告诉它将截取的屏幕以文件形式返回。
如果使用的是RemoteWebDriver() ,则方法应该如下
首先启动selenium java -jar selenium-server-standalone-2.25.0.jar
01 |
packagecom.example.tests; |
03 |
importjava.io.IOException; |
04 |
importjava.net.MalformedURLException; |
06 |
importorg.apache.commons.io.FileUtils; |
08 |
importorg.openqa.selenium.*; |
09 |
importorg.openqa.selenium.remote.*; |
10 |
public classSelenium2 { |
12 |
public voidtestRemoteWebDriverScreenShot() { |
14 |
DesiredCapabilities capability = DesiredCapabilities.internetExplorer(); |
15 |
WebDriver driver = null; |
17 |
driver = newRemoteWebDriver( |
18 |
newURL("http://localhost:4444/wd/hub"), capability); |
19 |
} catch(MalformedURLException e) { |
22 |
driver.get("http://www.sina.com.cn"); |
24 |
driver = newAugmenter().augment(driver); |
26 |
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); |
28 |
FileUtils.copyFile(scrFile, newFile("D:\\screenshot.png")); |
29 |
} catch(IOException e) { |