多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

如何使用WebDriver进行屏幕截图-自动化测试

更新时间:2022-05-05 09:21:48 作者:多测师 浏览:332

  例: 打开百度首页 ,进行截图

  package com.example.tests;

  import java.io.File;

  import org.apache.commons.io.FileUtils;

  import org.junit.*;

  import org.openqa.selenium.*;

  import org.openqa.selenium.ie.InternetExplorerDriver;

  public class Selenium2 {

  @Test

  public void testTakesScreenshot() {

  WebDriver driver = new InternetExplorerDriver();

  driver.get("http://www.baidu.com");

  try {

  File srcFile = ((TakesScreenshot)driver).

  getScreenshotAs(OutputType.FILE);

  FileUtils.copyFile

  (srcFile,new File("d:\\screenshot.png"));

  } catch (Exception e) {

  e.printStackTrace();

  }

  driver.close();

  }

  }

  TakesScreenshot接口提供了getScreenshotAs()方法来捕捉屏幕。上面的例子中,我们指定了OutputType.FILE作为参数传递给getScreenshoAs()方法,告诉它将截取的屏幕以文件形式返回。

  如果使用的是RemoteWebDriver() ,则方法应该如下

  首先启动selenium java -jar selenium-server-standalone-2.25.0.jar

如何使用WebDriver进行屏幕截图-自动化测试

  package com.example.tests;

  import java.io.File;

  import java.io.IOException;

  import java.net.MalformedURLException;

  import java.net.URL;

  import org.apache.commons.io.FileUtils;

  import org.junit.*;

  import org.openqa.selenium.*;

  import org.openqa.selenium.remote.*;

  public class Selenium2 {

  @Test

  public void testRemoteWebDriverScreenShot() {

  //指定使用的浏览器

  DesiredCapabilities capability = DesiredCapabilities.internetExplorer();

  WebDriver driver = null;

  try {

  driver = new RemoteWebDriver( //我使用localhost来测试

  new URL("http://localhost:4444/wd/hub"), capability);

  } catch (MalformedURLException e) {

  e.printStackTrace();

  }

  driver.get("http://www.sina.com.cn");

  //对远程系统进行截图

  driver = new Augmenter().augment(driver);

  File scrFile =

  ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

  try {

  FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));

  } catch (IOException e) {

  e.printStackTrace();

  }

  }

  }

  以上内容为大家介绍了自动化测试中的如何使用WebDriver进行屏幕截图,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部