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