- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to take partial screenshot (frame) with Selenium WebDriver?
Whenever we encounter a failure during testing, it is a common nature to capture the screenshots wherever there is a deviation from the expected result. Thus it is considered a mandatory step to attach a screenshot for creating a bug.
While automating a bunch of test cases of a considerable number, capturing screenshot is critical to infer why a test case has failed for both the development and testing team. As they debug the failures, going through the screenshot and conclude if the failure is due to script issue or defect in the application.
Sometimes we may need to capture the screenshot of a particular element. Here we have to capture the entire page screenshot then crop that image as per the location and dimension of the element.
Example
Code Implementation.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.Point; import java.awt.image.BufferedImage; public class ScrshtElemnt{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url ="https://www.tutorialspoint.com/about/about_careers.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify logo WebElement l=driver.findElement(By.xpath( "//*[@class='top-logo']")); // capture screenshot and store the image File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); BufferedImage f = ImageIO.read(s); //location of webelement Point location= l.getLocation(); // Dimension of element int w= l.getSize().getWidth(); int h=l.getSize().getHeight(); // Image Crop BufferedImage cImage= f.getSubimage(location.getX(), location.getY(), w, h); ImageIO.write(cImage, "png", s); FileUtils.copyFile(s, new File("tutorialspointlogo.png")); driver.quit(); } }