是否可以使用Selenium WebDriver进行截图?
(注:不含硒遥控器)
是否可以使用Selenium WebDriver进行截图?
(注:不含硒遥控器)
当前回答
是的,可以使用Selenium WebDriver对网页进行快照。
WebDriver API提供的getScreenshotAs()方法为我们做了这项工作。
语法:getScreenshotAs(OutputType<X> target)
返回类型:X
参数:target—查看OutputType提供的选项
适用性:不特定于任何DOM元素
例子:
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
有关详细信息,请参阅下面的工作代码片段。
public class TakeScreenShotDemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http: //www.google.com”);
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
// Creating a destination file
File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
try {
FileUtils.copyFile(file, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
访问Snapshot using WebDriver获取更多详细信息。
其他回答
C#
public static void TakeScreenshot(IWebDriver driver, String filename)
{
// Take a screenshot and save it to filename
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(filename, ImageFormat.Png);
}
Java
我解决了这个问题。你可以扩展RemoteWebDriver,给它所有的接口,它的代理驱动程序实现:
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
JavaScript (Selenium-Webdriver)
driver.takeScreenshot().then(function(data){
var base64Data = data.replace(/^data:image\/png;base64,/,"")
fs.writeFile("out.png", base64Data, 'base64', function(err) {
if(err) console.log(err);
});
});
PHP (PHPUnit)
它使用PHPUnit_Selenium扩展版本1.2.7:
class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
...
public function screenshot($filepath) {
$filedata = $this->currentScreenshot();
file_put_contents($filepath, $filedata);
}
public function testSomething() {
$this->screenshot('/path/to/screenshot.png');
}
...
}
PHP
public function takescreenshot($event)
{
$errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";
if(!file_exists($errorFolder)){
mkdir($errorFolder);
}
if (4 === $event->getResult()) {
$driver = $this->getSession()->getDriver();
$screenshot = $driver->getWebDriverSession()->screenshot();
file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' . time() . '.png', base64_decode($screenshot));
}
}