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