用Selenium WebDriver截图

有谁知道是否有可能使用Selenium WebDriver截图? (注意:不是Selenium RC)

Java的

是的,这是可能的。 以下示例在Java中:

WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com/"); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Now you can do whatever you need to do with it, for example copy somewhere FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png")); 

python

每个WebDriver都有一个.save_screenshot(filename)方法。 所以对于Firefox,可以这样使用:

 from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com/') browser.save_screenshot('screenie.png') browser.quit() 

令人困惑的是, .get_screenshot_as_file(filename)方法同样存在。

还有一些方法: .get_screenshot_as_base64() (用于embeddedhtml)和.get_screenshot_as_png() (用于检索二进制数据)。

并注意WebElements有一个类似的.screenshot()方法,但只捕获选定的元素。

C#

 public void TakeScreenshot() { try { Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot(); ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception e) { Console.WriteLine(e.Message); throw; } } 

ruby

 require 'rubygems' require 'selenium-webdriver' driver = Selenium::WebDriver.for :ie driver.get "https://www.google.com" driver.save_screenshot("./screen.png") 

更多的文件types和选项可用,你可以在takes_screenshot.rb中看到它们

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'); } ... } 

Java的

我解决了这个问题。 您可以扩充RemoteWebDriver为其提供所有代理驱动程序实现的接口:

 WebDriver augmentedDriver = new Augmenter().augment(driver); ((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way 

C#

 public Bitmap TakeScreenshot(By by) { // 1. Make screenshot of all screen var screenshotDriver = _selenium as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray)); // 2. Get screenshot of specific element IWebElement element = FindElement(by); var cropArea = new Rectangle(element.Location, element.Size); return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat); } 

Java的

 public String captureScreen() { String path; try { WebDriver augmentedDriver = new Augmenter().augment(driver); File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE); path = "./target/screenshots/" + source.getName(); FileUtils.copyFile(source, new File(path)); } catch(IOException e) { path = "Failed to capture screenshot: " + e.getMessage(); } return path; } 

Jython的

 import org.openqa.selenium.OutputType as OutputType import org.apache.commons.io.FileUtils as FileUtils import java.io.File as File import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver self.driver = FirefoxDriver() tempfile = self.driver.getScreenshotAs(OutputType.FILE) FileUtils.copyFile(tempfile, File("C:\\screenshot.png")) 

Java(机器人框架)

我用这个方法拍摄屏幕截图。

 void takeScreenShotMethod(){ try{ Thread.sleep(10000) BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg")); } catch(Exception e){ e.printStackTrace(); } } 

您可以根据需要使用此方法。

python

您可以使用python web驱动程序从窗口捕捉图像。 使用下面哪个页面需要截取截图的代码

 driver.save_screenshot('c:\foldername\filename.extension(png,jpeg)') 

Java的

似乎在这里丢失 – 在Java中的特定元素截图:

 public void takeScreenshotElement(WebElement element) throws IOException { WrapsDriver wrapsDriver = (WrapsDriver) element; File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE); Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height); Point location = element.getLocation(); BufferedImage bufferedImage = ImageIO.read(screenshot); BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height); ImageIO.write(destImage, "png", screenshot); File file = new File("//path//to"); FileUtils.copyFile(screenshot, file); } 

Java的

我无法得到可以接受的答案,但根据目前的WebDriver文档 ,以下OS X 10.9上的Java 7对我来说工作得很好:

 import java.io.File; import java.net.URL; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class Testing { public void myTest() throws Exception { WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444/wd/hub"), DesiredCapabilities.firefox()); driver.get("http://www.google.com"); // RemoteWebDriver does not implement the TakesScreenshot class // if the driver does have the Capabilities to take a screenshot // then Augmenter will add the TakesScreenshot methods to the instance WebDriver augmentedDriver = new Augmenter().augment(driver); File screenshot = ((TakesScreenshot)augmentedDriver). getScreenshotAs(OutputType.FILE); } } 

ruby(黄瓜)

 After do |scenario| if(scenario.failed?) puts "after step is executed" end time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M') file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png' page.driver.browser.save_screenshot file_path end Given /^snapshot$/ do time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M') file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png' page.driver.browser.save_screenshot file_path end 

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)); } } 

电源shell

 Set-Location PATH:\to\selenium Add-Type -Path "Selenium.WebDriverBackedSelenium.dll" Add-Type -Path "ThoughtWorks.Selenium.Core.dll" Add-Type -Path "WebDriver.dll" Add-Type -Path "WebDriver.Support.dll" $driver = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver $driver.Navigate().GoToUrl("https://www.google.co.uk/") # Take a screenshot and save it to filename $filename = Join-Path (Get-Location).Path "01_GoogleLandingPage.png" $screenshot = $driver.GetScreenshot() $screenshot.SaveAsFile($filename, [System.Drawing.Imaging.ImageFormat]::Png) 

其他司机…

 $driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver $driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver $driver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver $driver = New-Object OpenQA.Selenium.Opera.OperaDriver 

C#

 using System; using OpenQA.Selenium.PhantomJS; using System.Drawing.Imaging; namespace example.com { class Program { public static PhantomJSDriver driver; public static void Main(string[] args) { driver = new PhantomJSDriver(); driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024); driver.Navigate().GoToUrl("http://www.example.com/"); driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png); driver.Quit(); } } } 

需要NuGetPackages:

  1. PhantomJS 2.0.0
  2. selenium。支持2.48.2
  3. Selenium.WebDriver 2.48.2

使用.NETFramework v4.5.2进行testing

ruby

 time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S') file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png' #driver.save_screenshot(file_path) page.driver.browser.save_screenshot file_path 

python

 def test_url(self): self.driver.get("https://www.google.com/") self.driver.save_screenshot("test.jpg") 

它会将屏幕保存到保存脚本的同一目录中。

Java的

 public void captureScreenShot(String obj) throws IOException { File screenshotFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(screenshotFile,new File("Screenshots\\"+obj+""+GetTimeStampValue()+".png")); } public String GetTimeStampValue()throws IOException{ Calendar cal = Calendar.getInstance(); Date time=cal.getTime(); String timestamp=time.toString(); System.out.println(timestamp); String systime=timestamp.replace(":", "-"); System.out.println(systime); return systime; } 

使用这两种方法,您也可以使用date和时间进行屏幕截图。

Java的

使用RemoteWebDriver,在增加具有截图function的节点之后,我将存储如下所示的截图:

 void takeScreenShotMethod(){ try{ Thread.sleep(10000); long id = Thread.currentThread().getId(); BufferedImage image = new Robot().createScreenCapture(new Rectangle( Toolkit.getDefaultToolkit().getScreenSize())); ImageIO.write(image, "jpg", new File("./target/surefire-reports/" + id + "/screenshot.jpg")); } catch( Exception e ) { e.printStackTrace(); } } 

您可以根据需要使用此方法。 然后,我假设你可以在surefire-reports / html / custom.css中定制maven-surefire-report-plugin的样式表,以便你的报告包含每个testing正确屏幕截图的链接。

Java的

 String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername"; // take a snapshort File snapshort_file = ((TakesScreenshot) mWebDriver) .getScreenshotAs(OutputType.FILE); // copy the file into folder FileUtils.copyFile(snapshort_file, new File(yourfilepath)); 

希望这可以解决你的问题

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); } 

Selenese的

 captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd 

C#

您可以使用下面的代码片段/函数来使用selenium进行截图:

  public void TakeScreenshot(IWebDriver driver, string path = @"output") { var cantakescreenshot = (driver as ITakesScreenshot) != null; if (!cantakescreenshot) return; var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond; filename = path + @"\" + filename + ".png"; var ss = ((ITakesScreenshot)driver).GetScreenshot(); var screenshot = ss.AsBase64EncodedString; byte[] screenshotAsByteArray = ss.AsByteArray; if (!Directory.Exists(path)) Directory.CreateDirectory(path); ss.SaveAsFile(filename, ImageFormat.Png); } 

C#(Ranorex API)

 public static void ClickButton() { try { // code } catch (Exception e) { TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true); Report.Screenshot(); throw (e); } } 

Java的

以为我会给我完整的解决scheme,因为有两种不同的方式获取屏幕截图。 一个来自本地浏览器,另一个来自远程浏览器。 我甚至将图像embedded到html报告中

 @After() public void selenium_after_step(Scenario scenario) throws IOException, JSONException { if (scenario.isFailed()){ scenario.write("Current URL = " + driver.getCurrentUrl() + "\n"); try{ driver.manage().window().maximize(); //Maximize window to get full screen for chrome }catch (org.openqa.selenium.WebDriverException e){ System.out.println(e.getMessage()); } try { if(isAlertPresent()){ Alert alert = getAlertIfPresent(); alert.accept(); } byte[] screenshot; if(false /*Remote Driver flow*/) { //Get Screen shot from remote driver Augmenter augmenter = new Augmenter(); TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver); screenshot = ts.getScreenshotAs(OutputType.BYTES); } else { //get screen shot from local driver //local webdriver user flow screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); } scenario.embed(screenshot, "image/png"); //Embed image in reports } catch (WebDriverException wde) { System.err.println(wde.getMessage()); } catch (ClassCastException cce) { cce.printStackTrace(); } } //seleniumCleanup(); } 

selenium/ Java

以下是Selenide项目如何实现,比其他任何方式都容易:

 import static com.codeborne.selenide.Selenide.screenshot; screenshot("my_file_name"); 

对于Junit:

 @Rule public ScreenShooter makeScreenshotOnFailure = ScreenShooter.failedTests().succeededTests(); 

对于TestNG:

 import com.codeborne.selenide.testng.ScreenShooter; @Listeners({ ScreenShooter.class})