About this lesson
Take an element screenshot in Selenium Java with WebElement.getScreenshotAs()
Learn Selenium JavaAdvancedScreenshots
How it works
Selenium 4 lets you capture a single element: WebElement extends TakesScreenshot, so element.getScreenshotAs(OutputType.FILE) returns a PNG cropped to that element's box. No cast is needed.
The crop is of what the browser shows. An element entirely below the viewport is scrolled into view first, but one that is only partly visible is not. In the runner's default window, the left-click button on the Buttons page sits right at the bottom edge with one pixel row showing, and its screenshot comes back 1 pixel high even though the button is 34 pixels tall. The file exists and has content, so a size check alone does not catch it.
Hidden elements still produce an image of their box, just without visible content. A screenshot is evidence of what was drawn, so check the element's state as well.
About the assignment
The starter finds the left-click button. You capture just that button as a file and check that the file exists and has content.
What you will do
- Call
getScreenshotAs()on the button withOutputType.FILE. - Print whether the file exists after the label
Element screenshot taken:. - Print whether its length is greater than zero after the label
Element screenshot has content:.
Common mistakes
Not scrolling the element fully into view
A partly visible element is captured partly. Scroll it into view first, for example with
scrollIntoView()as in lesson 59, when the image matters.Casting the element
There is no need.
WebElementalready hasgetScreenshotAs().Comparing images pixel by pixel
Fonts and anti-aliasing differ between machines, so exact comparisons fail. Visual testing tools compare with a tolerance.
In a real test suite
Element screenshots suit visual checks of a single component, such as a chart, a badge or a generated QR code, and make failure reports easier to read than a full-page capture.
Lesson 62 captured the viewport. Lesson 64 moves to the Tables page and starts reading table data, beginning with the header row.
Related lessons
- Take Viewport ScreenshotCapture the whole viewport.
- Scroll to Element with JavaScriptScroll an element fully into view before capturing it.
- Window Size and PositionA larger window keeps more elements fully on screen.
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Elements/Buttons");
WebElement button = driver.findElement(By.id("leftClick"));
// TODO: Take screenshot of the button element
// TODO: Verify the file exists and has content
driver.quit();
}
}