selenium捕获提示
Capturing screenshots is essential to find out if your web-application is rendering seamlessly, and where it's failing if not.
捕获屏幕截图对于确定您的Web应用程序是否正在无缝渲染以及在哪里失败是至关重要的。
Traditionally, testers were accustomed to capturing screenshots manually for each and every test they ran, which was painstakingly exhausting and time-consuming. However, the introduction of Selenium allowed testers to automated browser testing and testers relied on Selenium screenshots to automatically capture their web-application in multiple browsers or environments without the extra hassle.
传统上,测试人员习惯于为他们进行的每项测试手动捕获屏幕截图,这非常费力且费时。 但是, Selenium的引入使测试人员可以自动进行浏览器测试,并且测试人员可以依靠Selenium屏幕截图自动在多个浏览器或环境中捕获其Web应用程序,而不会带来额外的麻烦。
In this article, we’re going to deep dive into Selenium Screenshots. We will learn how to capture screenshots in Selenium in different ways. But before we do that, let’s recap on the importance of capturing screenshots in Selenium.
在本文中,我们将深入研究Selenium屏幕截图。 我们将学习如何以不同的方式捕获Selenium中的屏幕截图。 但是在此之前,让我们先回顾一下在Selenium中捕获屏幕截图的重要性。
为什么在Selenium测试中捕获屏幕截图很重要? (Why Is It Important To Capture Screenshots In Selenium Testing?)
The entire point of implementing Selenium test automation is to execute tests without interference and get results instantaneously. Wouldn’t be it good to have an image at hand for when you find a bug? You never know when a test might fail and all your effort will be in vain if you have no proof of the bug. As the saying goes, a picture is worth a thousand words.
实施Selenium测试自动化的重点在于执行测试而不会产生干扰,并即时获得结果。 发现错误时手头有图像会不好吗? 您永远不知道什么时候测试可能会失败,并且如果您没有该bug的证明,您的所有努力将是徒劳的。 俗话说,一张图片值得一千个字。
That’s why capturing a Selenium screenshot is an important step in testing — it helps you to:
这就是为什么捕获Selenium屏幕截图是测试中重要的一步-它可以帮助您:
- Understand the end to end flow of a web application 了解Web应用程序的端到端流程
- Analyze a bug 分析错误
- Track test execution 跟踪测试执行
- Analyze the behavior of the test in different browsers/environments 在不同的浏览器/环境中分析测试的行为
- Trace and examine the reason behind test failure 跟踪并检查测试失败的原因
何时在Selenium测试中捕获屏幕截图 (When to Capture Screenshots in Selenium Testing)
Selenium screenshots can help you analyze anything, from a bug to a web element. These are the possible scenarios where you might consider capturing a Selenium screenshot:
Selenium屏幕截图可以帮助您分析任何内容,从错误到Web元素。 这些是您可能考虑捕获Selenium屏幕截图的可能方案:
- For each and every test case 对于每个测试用例
- Only when there is a failure 只有失败了
- At a specific time interval 在特定的时间间隔
- In different browsers 在不同的浏览器中
- Of specific elements on a webpage 网页上的特定元素
- At specific checkpoints 在特定的检查站
Now, I will show you how to capture a screenshot in Selenium in various different ways.
现在,我将向您展示如何以各种不同方式在Selenium中捕获屏幕截图。
如何使用Selenium Webdriver截屏 (How to Take a Screenshot Using the Selenium Webdriver)
The basic concepts on which the Selenium screenshot capture relies are typecasting and file handling. The screenshot in Selenium is captured and stored in a specified destination provided in the Selenium testing script.
Selenium屏幕截图捕获所依赖的基本概念是类型转换和文件处理。 Selenium中的屏幕截图将被捕获并存储在Selenium测试脚本中提供的指定目标中。
While automating a web application, we can use an interface TakesScreenshot
that signals the WebDriver
to take a screenshot during test execution. The TakesScreenshot
interface is extended by the WebElement
interface (an interface extends another interface) and the browser driver classes such as FirefoxDriver
, ChromeDriver
, OperaDriver
, etc implement the same interface (a class implements an interface).
在自动化Web应用程序时,我们可以使用接口TakesScreenshot
,该接口向WebDriver
发送信号以在测试执行期间截取屏幕截图。 TakesScreenshot
接口由WebElement
接口扩展(一个接口扩展了另一个接口),并且诸如FirefoxDriver
, ChromeDriver
, OperaDriver
等浏览器驱动程序类实现了相同的接口(一个类实现了一个接口)。
RemoteWebDriver()
class implements interfaces like WebDriver()
,and TakesScreenshot()
. To access these methods we have to downcast the driver object:
RemoteWebDriver()
类实现WebDriver()
和TakesScreenshot()
类的接口。 要访问这些方法,我们必须向下转换驱动程序对象:
WebDriver driver = new ChromeDriver();
TakesScreenshot ts = (TakesScreenshot)driver;
The method getScreenshotAs()
in the interface TakesScreenshot
helps in capturing the screenshots and storing them in a specified path. We have another interface, OutputType
, which is used to specify the output format of the screenshot such as FILE
andBYTES
.
接口TakesScreenshot
中的getScreenshotAs()
方法有助于捕获屏幕快照并将其存储在指定的路径中。 我们还有另一个接口OutputType
,用于指定屏幕截图的输出格式,例如FILE
和BYTES
。
File file = ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,new File (“./ScreenShot_Folder/Test1_Login.png”));
In the above destination path ./
indicates the current directory. We can specify the subfolder to hold the screenshots taken and the name in which the screenshots have to be saved. As per the above line, the screenshot taken would be stored in the ScreenShot_Folder
subfolder inside the current working directory in the name of Test1_Login.png
file. If the given subfolder doesn’t exist, then on first-time execution of the script the folder gets automatically created.
在上述目标路径中,. ./
表示当前目录。 我们可以指定子文件夹来保存拍摄的屏幕快照,以及必须保存屏幕快照的名称。 按照上面的代码行,所截取的屏幕截图将存储在ScreenShot_Folder
Test1_Login.png
文件名在当前工作目录中的Test1_Login.png
文件夹。 如果给定的子文件夹不存在,则在首次执行脚本时,将自动创建文件夹。
1.在Selenium WebDriver中捕获屏幕截图的简单程序 (1. A Simple Program To Capture a Screenshot In Selenium WebDriver)
Scenario: Navigate to a webpage, enter valid credentials, and take a screenshot of the page before clicking the Login button. Once logged in, verify if an employee record exists in the employee list and capture a screenshot.
场景:在单击“登录”按钮之前,导航至网页,输入有效的凭据,并对该页面进行截图。 登录后,验证员工列表中是否存在员工记录并捕获屏幕截图。
package com.LoginTest;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class LoginPage {
public WebDriver driver;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\shalini\\Downloads\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void loginTest() {
//define the url
driver.get("https://opensource-demo.orangehrmlive.com/");
//maximize the window
driver.manage().window().maximize();
//delete the cookies saved
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//get the title of the webpage
String pageTitle = driver.getTitle();
System.out.println("The title of this page is ===> " +pageTitle);
//enter the locator of username and clear the input field before entering any value
driver.findElement(By.id("txtUsername")).clear();
//enter the username
driver.findElement(By.id("txtUsername")).sendKeys("Admin");
//enter the locator of password and clear the input field
driver.findElement(By.id("txtPassword")).clear();
//enter the value of password
driver.findElement(By.id("txtPassword")).sendKeys("admin123");
//downcast the driver to access TakesScreenshot method
TakesScreenshot ts = (TakesScreenshot)driver;
//capture screenshot as output type FILE
File file = ts.getScreenshotAs(OutputType.FILE);
try {
//save the screenshot taken in destination path
FileUtils.copyFile(file, new File("./ScreenShot_Folder/Test1_Login.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("the login page screenshot is taken");
//enter the locator of login button and click
driver.findElement(By.id("btnLogin")).click();
//wait for the page to load
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
//search an employee by providing the name,role and status
driver.findElement(By.linkText("Admin")).click();
driver.findElement(By.xpath("//input[@id = 'searchSystemUser_userName']")).clear();
driver.findElement(By.xpath("//input[@id = 'searchSystemUser_userName']")).sendKeys("Chris Evans");
Select selectRole = new Select(driver.findElement(By.id("searchSystemUser_userType")));
selectRole.selectByVisibleText("Admin");
driver.findElement(By.id("searchSystemUser_employeeName_empName")).clear();
driver.findElement(By.id("searchSystemUser_employeeName_empName")).sendKeys("Test 1");
Select selectStatus = new Select (driver.findElement(By.id("searchSystemUser_status")));
selectStatus.selectByVisibleText("Enabled");
driver.findElement(By.id("searchBtn")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
TakesScreenshot ts1 = (TakesScreenshot)driver;
File file1 = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(file1, new File("./ScreenShot_Folder/Test2_SearchUser.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("the userStatus screenshot is taken");
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
TestNG.xml (TestNG.xml)
Once the test has been executed, refresh the project. A new subfolder would be created as mentioned in the script and you will see the Selenium screenshot saved in the path.
执行完测试后,刷新项目。 如脚本中所述,将创建一个新的子文件夹,您将在路径中看到Selenium屏幕截图。
Below are the captured screenshots.
以下是捕获的屏幕截图。
The first Selenium screenshot shows the login page of the website.
第一个Selenium屏幕截图显示了网站的登录页面。
The second Selenium screenshot shows the search result of an employee.
第二张Selenium屏幕截图显示了员工的搜索结果。
2.如何仅在故障期间捕获Selenium中的屏幕截图 (2. How To Capture A Screenshot In Selenium Only During Failure)
In our Selenium test automation suite, we may have lots of test cases to be executed. Sometimes capturing screenshots for each and every test case wouldn’t be required. In such cases, we can capture the screenshots only when a failure occurs in the execution. To achieve this, we could use the ITestListener
interface from TestNG
. If you’re new to TestNG then you can refer to our guide on TestNG Listeners.
在我们的Selenium测试自动化套件中,我们可能要执行很多测试用例。 有时,不需要为每个测试用例捕获屏幕截图。 在这种情况下,我们只能在执行失败时捕获屏幕截图。 为此,我们可以使用TestNG
的ITestListener
接口。 如果您不熟悉TestNG,则可以参考我们的有关TestNG侦听器的指南。
Scenario: Navigate to a webpage, enter the credentials, and click the login button.
场景:导航至网页,输入凭据,然后单击登录按钮。
We split the above scenario into two cases:
我们将上述情况分为两种情况:
- Test case one: Navigate to a webpage 测试案例一:导航至网页
Test case two: Enter the username and password and click Login
测试案例二: 输入用户名和密码,然后单击登录。
In case of failure in any test case, a screenshot would be captured and stored in the destination path.
如果在任何测试用例中均失败,则将捕获屏幕快照并将其存储在目标路径中。
To achieve this, first, we have to create a Listener
class. This class implements the ITestListener
interface. Then click “Add unimplemented methods.”
为此,首先,我们必须创建一个Listener
类。 此类实现ITestListener
接口。 然后单击“添加未实现的方法”。
After adding all the methods, your code will look like this:
添加所有方法后,您的代码将如下所示:
package com.LoginTest;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class ListenerClass implements ITestListener{
@Override
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
@Override
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}
@Override
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
}
}
Now we can set up the point where the Selenium screenshot has to be taken. In our case, we have to capture a screenshot in Selenium only when a failure occurs.
现在我们可以设置必须拍摄Selenium屏幕截图的位置。 在我们的情况下,只有在发生故障时,我们才必须在Selenium中捕获屏幕截图。
We can modify the onTestFailure()
method to take a screenshot:
我们可以修改onTestFailure()
方法来截取屏幕截图:
@Override
public void onTestFailure(ITestResult result) {
// TODO Auto-generated method stub
TakesScreenshot ts = (TakesScreenshot)FacebookLogin.driver;
File file = ts.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(file, new File(“./ScreenShot_Folder/TestFailure.png”));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“screenshot is taken”);
}
两个测试的代码段 (Code snippet for two tests)
Test case one: Navigate to the Facebook login page, get the title of the page and check if the page title matches with the original one “
Facebook - log in or sign up
"测试案例一:导航至Facebook登录页面,获取页面标题,并检查页面标题是否与原始页面“
Facebook - log in or sign up
”相匹配Test case two: Enter the credentials and click the login button, get the title of the page and check if the page title matches the original title “Facebook”. Only upon successful login, we would be able to get this title.
测试案例二:输入凭据并单击登录按钮,获取页面标题,然后检查页面标题是否与原始标题“ Facebook”匹配。 只有成功登录后,我们才能获得此标题。
In order to capture screenshots in failed cases, I have intentionally failed the login test case by providing invalid credentials — which by the way wouldn’t be redirected to the actual page, thereby causing a failure because of the page title mismatch.
为了在失败的情况下捕获屏幕截图,我故意通过提供无效的凭据使登录测试用例失败-顺便说一句,该凭据将不会重定向到实际页面,从而由于页面标题不匹配而导致失败。
package com.fbLoginPage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
@Listeners (ListenerClass.class)
public class FacebookLogin {
public static WebDriver driver;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\shalini\\Downloads\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void browsePageTest() {
//define the url
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//get the title of the webpage
String pageTitle = driver.getTitle();
System.out.println("The title of this page is ===> " +pageTitle);
Assert.assertEquals(pageTitle, "Facebook – log in or sign up");
}
@Test
public void loginTest() {
//clear the input field before entering any value
driver.findElement(By.xpath("//input[@id='email']")).clear();
driver.findElement(By.xpath("//input[@id='email']")).sendKeys("[email protected]");
//enter the locator of username
driver.findElement(By.xpath("//input[@id='pass']")).clear();
driver.findElement(By.xpath("//input[@id='pass']")).sendKeys("1234567890");
driver.findElement(By.id("loginbutton")).click();
String loginPageTitle = driver.getTitle();
Assert.assertEquals(loginPageTitle, "Facebook");
}
@AfterClass
public void tearDown() {
driver.quit();
}
}
TestNG.xml (TestNG.xml)
!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
控制台输出 (Console output)
Once the tests are executed, refresh the project. A Selenium screenshot of the failed test is saved:
执行测试后,刷新项目。 测试失败的Selenium屏幕截图已保存:
3.如何在Selenium中捕获特定WebElement的屏幕截图 (3. How to Capture a Screenshot in Selenium for a Specific WebElement)
Selenium not only provides the option of capturing screenshots of WebPages but also the WebElements that are interacted with. Import the class javax.imageio
. ImageIO provides ImageReader and ImageWriter plugins which are used to crop the image of specified WebElement in the webpage using height, width, and coordinates parameters.
Selenium不仅提供捕获网页截图的选项,而且还提供与之交互的WebElement的捕获。 导入类javax.imageio
。 ImageIO提供了ImageReader和ImageWriter插件,用于使用高度,宽度和坐标参数来裁剪网页中指定WebElement的图像。
- Scenario: Navigate to the Facebook page, enter the credentials, and click the login button. 场景:浏览至Facebook页面,输入凭据,然后单击登录按钮。
- Capture the screenshot of the Facebook logo and a login button: 捕获Facebook徽标和登录按钮的屏幕截图:
package com.LoginPage.LogoTest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ElementCaptureTest {
public static WebDriver driver;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\shalini\\Downloads\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void browsePageTest() throws IOException {
//navigate to the webPage
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String pageTitle = driver.getTitle();
System.out.println("The title of this page is ===> " +pageTitle);
Assert.assertEquals(pageTitle, "Facebook – log in or sign up");
//identify the locator of the WebElement – FaceBook Logo
WebElement fbLogo = driver.findElement(By.xpath("//*[@id=\"blueBarDOMInspector\"]/div/div/div/div[1]"));
takeScreenshotOfElement(fbLogo);
//identify the locator of the WebElement – Login Button
WebElement loginButton = driver.findElement(By.id("loginbutton"));
takeScreenshotOfElement(loginButton);
}
@AfterClass
public void tearDown() {
driver.quit();
}
public static void takeScreenshotOfElement(WebElement element) throws IOException {
//capture the screenshot of full page
TakesScreenshot ts = (TakesScreenshot)driver;
File file = ts.getScreenshotAs(OutputType.FILE);
// read the screenshot image
BufferedImage fullScreen = ImageIO.read(file);
//get the width and height of the element
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
//get the X and Y coordinates of the webElement
Point location = element.getLocation();
//get the image using height,width and coordinates
BufferedImage logoImage = fullScreen.getSubimage(location.getX(), location.getY(),width, height);
ImageIO.write(logoImage, "png", file);
//save the captured screenshot
Random random = new Random();
FileUtils.copyFile(file,new File("./ScreenShot_Folder/screenshot_Test"+random.nextInt()+".png"));
}
}
Facebook徽标 (Facebook Logo)
登录 (Login)
保存捕获的屏幕截图的不同方法 (Different Ways of Saving the Captured Screenshots)
To enhance readability, we can store the captured screenshot in Selenium by naming each of them dynamically. The two most preferred ways are:
为了提高可读性,我们可以通过动态命名捕获的屏幕快照来将捕获的屏幕快照存储在Selenium中。 两种最优选的方式是:
- Saving the captured screenshots based on the timestamp. 根据时间戳保存捕获的屏幕截图。
- Saving the captured screenshots based on random ID. 根据随机ID保存捕获的屏幕截图。
捕获截图并基于时间戳存储它们 (Capture Screenshots and Store Them Based on Timestamp)
Usually, when you name the Selenium screenshot in the code, each and every time when the test is executed the screenshot would be replaced. So to overcome this, we may use the timestamp logic to save the screenshot as multiple files that are named based on the timestamp in every test execution.
通常,当您在代码中命名Selenium屏幕截图时,每次执行测试时都会替换屏幕截图。 因此,为了克服这个问题,我们可以使用时间戳逻辑将屏幕快照保存为多个文件,这些文件将在每次测试执行中根据时间戳进行命名。
I have added a separate method to capture the screenshots and name them based on the current time of text execution. Different time formats could be used.
我添加了一个单独的方法来捕获屏幕截图并根据当前文本执行时间对其命名。 可以使用不同的时间格式。
package com.Loginpage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SaveScreenshotWithTime {
public static WebDriver driver;
@BeforeClass
public void setUp() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\shalini\\Downloads\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@Test
public void browsePageTest() {
driver.get("https://www.facebook.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String pageTitle = driver.getTitle();
System.out.println("The title of this page is ===> " +pageTitle);
Assert.assertEquals(pageTitle, "Facebook – log in or sign up");
try {
screenShot(driver);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@AfterClass
public void tearDown() {
driver.quit();
}
public static void screenShot (WebDriver driver) throws IOException, InterruptedException {
TakesScreenshot ts = (TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
File destination= new File("./ScreenShot_Folder/screenshot_"+timestamp()+".jpeg");
FileUtils.copyFile(source, destination);
}
public static String timestamp() {
return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
}
}
Once the tests are executed, the captured screenshots are saved in the desired path based on the timestamp.
一旦执行了测试,捕获的屏幕截图将根据时间戳保存在所需的路径中。
根据随机ID捕获屏幕截图并存储 (Capture Screenshots and Store, Based On Random ID)
We can use the random class in Java to generate random numbers and store the captured screenshots with this number.
我们可以使用Java中的random类生成随机数,并使用该数字存储捕获的屏幕截图。
We have to replace the timestamp logic used in previous code with the below:
我们必须将以下代码替换先前代码中使用的时间戳逻辑:
Random random = new Random();
FileUtils.copyFile(file,new File(“./ScreenShot_Folder/screenshot_Test”+random.nextInt()+”.png”));
Screenshots captured and saved by the random number generation logic:
随机数生成逻辑捕获并保存的屏幕截图:
Great! You have successfully captured Selenium Screenshots in different ways and learned how to save these screenshots. But what if I told you that there was an easier way to capture Selenium screenshots?
大! 您已经以不同的方式成功捕获了Selenium屏幕截图,并学习了如何保存这些屏幕截图。 但是,如果我告诉您,有一种更简单的方式来捕获Selenium屏幕截图怎么办?
捕获Selenium的最简单方法Screenshots (The Easiest Way to Capture Selenium Screenshots)
The easiest way to capture screenshots in Selenium is by using LambdaTest cloud Selenium Grid of 2000+ real browsers for desktop and mobile.
在Selenium中捕获屏幕截图的最简单方法是使用LambdaTest 云Selenium Grid(包含2000多种用于台式机和移动设备的真实浏览器)。
At LambdaTest, we want to make the Selenium testing experience as convenient as possible. This is why we provide a toggle button in our Selenium Desired Capabilities Generator.
在LambdaTest,我们希望使Selenium测试体验尽可能地方便。 这就是为什么我们在Selenium所需功能生成器中提供一个切换按钮的原因。
When turned on, this button adds a capability called visual
in the desired capabilities class and set its value as true
.
启用后,此按钮会在所需功能类中添加一个称为“ visual
”的功能,并将其值设置为true
。
If you pass this capability in your Desired Capabilities class while running your Selenium testing script on LambdaTest Selenium Grid then we’ll generate step-by-step screenshots for your Selenium automation script.
如果您在LambdaTest Selenium Grid上运行Selenium测试脚本时在Desired Capabilities类中传递了此功能,则我们将为Selenium自动化脚本生成分步屏幕截图。
You can find these step by step screenshots on the Automation dashboard, by going to Automation Logs > Metadata.
您可以转到自动化日志>元数据,在自动化仪表板上找到这些分步截图。
In the Metadata tab, you will find the button to Download All screenshots.
在“元数据”选项卡中,您将找到“ 下载所有屏幕截图”的按钮。
Porting your Selenium testing scripts to LambdaTest is easy. All you need to do is specify your LambdaTest username and access key as the environment variables to route your Selenium tests on a Remote WebDriver. Refer to our documentation on TestNG with Selenium.
将Selenium测试脚本移植到LambdaTest很容易。 您所需要做的就是指定LambdaTest用户名和访问密钥作为环境变量,以在远程WebDriver上路由Selenium测试。 请参阅我们有关带Selenium的TestNG的文档。
We also offer RESTful API for capturing Selenium Screenshots for automated browser testing.
我们还提供RESTful API,用于捕获Selenium屏幕截图以进行自动浏览器测试。
无需Selenium脚本即可捕获自动屏幕截图 (Capture Automated Screenshots Without Selenium Scripts)
We also offer a feature called Screenshot testing which allows you to capture full page screenshots of your website across 25 different browsers and operating systems. The tests can be executed either in desktop or mobile browsers.
我们还提供了一项称为“屏幕截图测试”的功能,该功能可让您跨25种不同的浏览器和操作系统捕获网站的全页屏幕截图。 可以在台式机或移动浏览器中执行测试。
You can create full-page screenshots, without writing any Selenium script, in two simple steps:
您可以通过两个简单的步骤创建完整的屏幕截图,而无需编写任何Selenium脚本:
- Step 1: Once logged in, click Visual UI Testing > Screenshot 步骤1:登录后,点击Visual UI Testing>屏幕截图
- Step 2: Enter the URL of the website you want to test, select the browser, and hit the capture button. 第2步:输入要测试的网站的URL,选择浏览器,然后单击“捕获”按钮。
This will automatically generate screenshots of your web-application on your selected browsers and operating systems.
这将在选定的浏览器和操作系统上自动生成Web应用程序的屏幕截图。
在登录后捕获屏幕截图 (Capture Screenshots Behind Login)
Step 1: To capture a screenshot behind login functionality, click the Login button, and create a New Login profile.
步骤1 :要捕获登录功能背后的屏幕快照,请单击“登录”按钮,然后创建一个“新登录”配置文件。
Step 2: Enter the URL of the webpage and click Next.
步骤2:输入网页的URL,然后单击Next(下一步)。
Step 3: Enter the locators of the username, password, and login button fields. Click Next.
步骤3:输入用户名,密码和登录按钮字段的定位符。 点击下一步。
You can select any of the locators as shown below:
您可以选择任何定位器,如下所示:
Step 4: Enter a valid username and password and click Next.
步骤4:输入有效的用户名和密码,然后单击Next(下一步)。
Step 5: Save the Login Profile.
步骤5:保存登录配置文件。
Step 6: Once saved, a profile is created:
步骤6:保存后,将创建一个配置文件:
For capturing a screenshot for the same webpage with the same credentials you can just toggle the user profile.
要使用相同的凭据捕获同一网页的屏幕截图,您只需切换用户个人资料即可。
Step 7: Select the browsers and the platform to execute the test and click Capture.
步骤7:选择浏览器和平台以执行测试,然后单击Capture(捕获)。
Once the test is executed in different browsers and platforms, the Selenium screenshots are captured and displayed:
在不同的浏览器和平台上执行测试后,将捕获并显示Selenium屏幕截图:
The screenshots can also be downloaded and verified.
屏幕截图也可以下载和验证。
利用自动截图API轻松进行跨浏览器测试 (Leverage Automated Screenshot API For Effortless Cross Browser Testing)
Execution of test cases in multiple browsers, environments, and devices takes a lot of work. Finding the compatible browser version and valid version of devices requires strenuous effort. Even though capturing the screenshots might seem to be a piece of cake, organizing the captured screenshots to track for future reference remains complicated.
在多个浏览器,环境和设备中执行测试用例需要大量的工作。 查找兼容的浏览器版本和设备的有效版本需要付出巨大的努力。 尽管捕获屏幕快照似乎只是小菜一碟,但组织捕获的屏幕快照以跟踪以供将来参考仍然很复杂。
LambdaTest provides an easy approach to capture screenshots through Automated Screenshot API and storing them by the device/platform followed by the browser version. This way it provides better readability and tracking. The platform in which the screenshot has to be captured while test execution has to be provided as a JSON object in the request body and multiple browser versions can be written in an array, which appears to be a straightforward approach to feeding the input.
LambdaTest提供了一种简单的方法,可通过自动截图API捕获截图,并按设备/平台和浏览器版本进行存储。 这样,它提供了更好的可读性和跟踪。 请求执行时必须在其中捕获屏幕快照的平台,而测试执行必须作为JSON对象提供,并且可以将多个浏览器版本写入一个数组,这似乎是提供输入的一种简单方法。
Let me show you an example of capturing screenshots across multiple environments through LambdaTest Automated screenshot API.
让我向您展示一个通过LambdaTest自动截图API在多个环境中捕获截图的示例。
Step 1: Navigate to https://www.lambdatest.com/support/docs/api-doc/#screenshots and select Automated Screenshots API tab. Click the Authorize button.
步骤1 :浏览至https://www.lambdatest.com/support/docs/api-doc/#screenshots,然后选择“自动截图API”标签。 单击授权按钮。
Step 2: Enter your username and access key which has been provided once you have signed into LambdaTest. Click Authorize.
第2步 :输入登录LambdaTest后提供的用户名和访问密钥。 单击授权。
Step 3: Click Start Screenshot Test and click Try it out.
步骤3 :单击“ 开始截图测试” ,然后单击“ 试用” 。
Step 4: To request this API to capture a screenshot, we have to construct a request body.
步骤4:要请求此API捕获屏幕截图,我们必须构造一个请求正文。
The HTTP method to capture the screenshot in this API is POST.
捕获此API中的屏幕快照的HTTP方法是POST。
The request body of the screenshot API is of ContextType
JSON and there are different tags that relay information about a webpage’s URL, the webpage to be automated, multiple browsers, platforms, devices on which the test has to be executed, resolution and layout of the screenshot, and the preference for sending the captured screenshots via mail.
屏幕快照API的请求主体为ContextType
JSON,并且有不同的标签来中继有关网页URL,要自动化的网页,多个浏览器,平台,必须在其上执行测试的设备,解决方案和布局的信息。屏幕截图,以及通过邮件发送捕获的屏幕截图的首选项。
A sample request body is given below:
样本请求正文如下:
{
“url”: “https://www.facebook.com",
“defer_time”: 5,
“email”: true,
“mac_res”: “1024x768”,
“win_res”: “1366X768”,
“smart_scroll”: true,
“layout”: “portrait”,
“configs”: {
“windows 10”: {
“chrome”: [
“76”,
“75”
],
“firefox”: [
“67”,
“66”
],
“opera”: [
“58”,
“57”
],
“ie”: [
“11”
]
},
“macos mojave”: {
“chrome”: [
“76”,
“75”
],
“firefox”: [
“67”,
“66”
],
“opera”: [
“58”,
“57”
],
“safari”: [
“12”
]
},
“ios 12.0”: {
“devices”: [
“iphone xr”,
“iphone xs”,
“iphone xs max”
]
},
“android 9.0”: {
“devices”: [
“galaxy s9 plus”
]
}
}
}
Step 5: Once after the request body is constructed, click Execute.
第5步 :构建请求正文后,点击Execute 。
Step 6: On successful execution, we could see the HTTP status code as 200 and test_id has been generated as a response.
步骤6:成功执行后,我们可以看到HTTP状态代码为200,并且已生成test_id作为响应。
Step 7: Navigate to the main page of the LambdaTest App and click the Test Logs tab. We can see the logs of all the tests that have been executed on this platform. To trace the screenshot test here, use the test_id that was generated as a successful response.
步骤7:导航到LambdaTest应用程序的主页,然后单击“ 测试日志”选项卡。 我们可以看到在该平台上执行的所有测试的日志。 要在此处跟踪屏幕快照测试,请使用作为成功响应生成的test_id。
On scrolling down, the screenshots captured in different browsers, platforms and devices as mentioned in the request body can be seen.
向下滚动时,可以看到在请求正文中提到的在不同浏览器,平台和设备中捕获的屏幕截图。
All the screenshots can also be downloaded in a ZIP file and then analyzed in detail. The screenshots would be named by the browser and its version, the platform, and the device in which the test was executed. This will ease the tracking of different test cases.
所有屏幕截图也可以下载为ZIP文件,然后进行详细分析。 屏幕截图将由浏览器及其版本,平台和执行测试的设备来命名。 这将简化对不同测试用例的跟踪。
In case of any incorrect information in the request body like an incorrect browser version or invalid name, an error response would be thrown with 400 status code and relevant error message.
如果请求正文中的任何错误信息(例如错误的浏览器版本或无效的名称),则会引发错误响应,并显示400状态代码和相关错误消息。
For example, if an invalid version of Google Chrome is given in request payload, an error response would be thrown.
例如,如果请求有效负载中给出了无效版本的Google Chrome,则会抛出错误响应。
要求正文 (Request body)
{
“url”: “https://www.facebook.com",
“defer_time”: 5,
“email”: true,
“mac_res”: “1024x768”,
“win_res”: “1366X768”,
“smart_scroll”: true,
“layout”: “portrait”,
“configs”: {
“windows 10”: {
“chrome”: [
“101”
]
}
}
}
响应 (Response)
Apart from the basic webpage screenshot, you can also try taking a screenshot for login functionality using the “Screenshot Test with Basic Authentication” option where you need to provide the username and password in the request body along with the other details seen before.
除了基本的网页屏幕截图外,您还可以尝试使用“具有基本身份验证的屏幕快照测试”选项来获取登录功能的屏幕截图,该屏幕截图需要在请求正文中提供用户名和密码以及之前看到的其他详细信息。
最后的想法 (Final Thoughts)
To summarize, I have walked you through the different ways to capture a screenshot in Selenium using the TakesScreenshot interface, ITestListener, ImageIO, Visual UI Testing and Automated Screenshot API in LambdaTest and various logics to save the captured screenshots. We have seen the importance of capturing Selenium screenshots in a web application.
总而言之,我向您介绍了使用TakesScreenshot界面,ITestListener,ImageIO,Visual UI Testing和LambdaTest中的自动截图API以及各种用于保存捕获的截图的逻辑来捕获Selenium中的截图的不同方法。 我们已经看到了在Web应用程序中捕获Selenium屏幕截图的重要性。
Understanding the end-to-end flow of a work product is important for any tester as he has to know the entire functionality before starting the Selenium test automation process. Capturing a Selenium screenshot in each step of the test execution provides clarity of the workflow and it also eases the tracking of each test case.
对于任何测试人员而言,了解工作产品的端到端流程都非常重要,因为他必须在开始Selenium测试自动化过程之前了解全部功能。 在测试执行的每个步骤中捕获Selenium屏幕截图,可以使工作流程更加清晰,还可以简化对每个测试用例的跟踪。
I hope you’ve gained knowledge in capturing a screenshot in selenium. Step up, try it hands-on and let me know your views on the comment section below. Feel free to share this with your colleagues and friends and as it might help in overcoming their challenges with the Selenium test automation script. Explore the automation features — until then happy testing!
希望您在捕获Selenium屏幕快照方面有所了解。 加大力度,动手尝试一下,并让我知道您对以下评论部分的看法。 随时与您的同事和朋友分享此内容,因为它可以帮助您克服Selenium测试自动化脚本中的挑战。 探索自动化功能-直到进行愉快的测试!
原始资料 (Original Source)
LambdaTest
LambdaTest
翻译自: https://medium.com/better-programming/how-to-capture-screenshots-in-selenium-c25643c33b89
selenium捕获提示