例: 打开百度首页 ,进行截图
01 |
package com.example.tests; |
02 |
import java.io.File; |
03 |
import org.apache.commons.io.FileUtils; |
04 |
import org.junit.*; |
05 |
import org.openqa.selenium.*; |
06 |
import org.openqa.selenium.ie.InternetExplorerDriver; |
07 |
public class Selenium2 { |
08 |
@Test |
09 |
public void testTakesScreenshot() { |
10 |
WebDriver driver = new InternetExplorerDriver(); |
11 |
driver.get( "http://www.baidu.com" ); |
12 |
try { |
13 |
File srcFile = ((TakesScreenshot)driver). |
14 |
getScreenshotAs(OutputType.FILE); |
15 |
FileUtils.copyFile |
16 |
(srcFile, new File( "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 |
package com.example.tests; |
02 |
import java.io.File; |
03 |
import java.io.IOException; |
04 |
import java.net.MalformedURLException; |
05 |
import java.net.URL; |
06 |
import org.apache.commons.io.FileUtils; |
07 |
import org.junit.*; |
08 |
import org.openqa.selenium.*; |
09 |
import org.openqa.selenium.remote.*; |
10 |
public class Selenium2 { |
11 |
@Test |
12 |
public void testRemoteWebDriverScreenShot() { |
13 |
//指定使用的浏览器 |
14 |
DesiredCapabilities capability = DesiredCapabilities.internetExplorer(); |
15 |
WebDriver driver = null ; |
16 |
try { |
17 |
driver = new RemoteWebDriver( //我使用localhost来测试 |
18 |
new URL( "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 = new Augmenter().augment(driver); |
25 |
File scrFile = |
26 |
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); |
27 |
try { |
28 |
FileUtils.copyFile(scrFile, new File( "D:\\screenshot.png" )); |
29 |
} catch (IOException e) { |
30 |
e.printStackTrace(); |
31 |
} |
32 |
} |
33 |
} |
转:WebDriver进行屏幕截图,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/lci05/p/3831502.html