Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

Currently I'm trying to capture a screenshot using the Selenium WebDriver. But I can only obtain the whole page screen shot. However, what I wanted is just to capture a part of the page or perhaps just on specific element based on ID or any specific element locator. (For example, I wish to capture the picture with image id = "Butterfly")

Is there any way to capture a screenshot by selected item or element?

like image 944
fj123 Avatar asked Dec 12 '12 03:12

fj123


People also ask

Can we take screenshot of single WebElement in Selenium?

A Screenshot in Selenium Webdriver is used for bug analysis. Selenium webdriver can automatically take screenshots during the execution. But if users need to capture a screenshot on their own, they need to use the TakeScreenshot method which notifies the WebDrive to take the screenshot and store it in Selenium.

How do you take a screenshot on WebElement?

Just pass the Webelement name and your file name in your generic “elementScreenshot” method. This will take three screenshots together. For the Target file in which you want to copy your source file, you can also give any path to store your screenshot.

How do I take a screenshot of a whole web page in Selenium?

To take a screenshot in Selenium, we use an interface called TakesScreenshot, which enables the Selenium WebDriver to capture a screenshot and store it in different ways. It has a got a method "getScreenshotAs() " which captures the screenshot and store it in the specified location.


1 Answers

We can get the element screenshot by cropping entire page screenshot as below:

driver.get("http://www.google.com"); WebElement ele = driver.findElement(By.id("hplogo"));  // Get entire page screenshot File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); BufferedImage  fullImg = ImageIO.read(screenshot);  // Get the location of element on the page Point point = ele.getLocation();  // Get width and height of the element int eleWidth = ele.getSize().getWidth(); int eleHeight = ele.getSize().getHeight();  // Crop the entire page screenshot to get only element screenshot BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),     eleWidth, eleHeight); ImageIO.write(eleScreenshot, "png", screenshot);  // Copy the element screenshot to disk File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png"); FileUtils.copyFile(screenshot, screenshotLocation); 
like image 51
Surya Avatar answered Oct 31 '22 15:10

Surya