Selenium with Java Syntaxes
Common Screenshot Methods
In selenium, we can take 3 types of screenshots
ViewPort Area (what's currently visible in the browser window).
WebElement (screenshot of only a particular HTML element on the page).
Full Page (Scrollable Content).
1. Capture the Current Viewport (Visible Area)
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ScreenshotCurrentViewport {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com"; // Example URL
driver.get(url);
driver.manage().window().maximize(); // Maximize for better view (optional)
// 1. Cast WebDriver to TakesScreenshot
TakesScreenshot ts = (TakesScreenshot) driver;
// 2. Get the screenshot as a File
File sourceFile = ts.getScreenshotAs(OutputType.FILE);
// 3. Define the destination file path
File destinationFile = new File("screenshots/current_viewport_" + System.currentTimeMillis() + ".png");
// 4. Copy the source file to the destination
sourceFile.renameTo(destinationFile);
System.out.println("Screenshot taken and saved to: " + destinationFile.getAbsolutePath());
driver.quit();
}
}
1. Capture the Current Viewport (Visible Area)
This is the most common and straightforward method. It takes a screenshot of what's currently visible in the browser window.
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils; // For FileUtils.copyFile
import io.github.bonigarcia.wdm.WebDriverManager; // Optional: For automatic driver setup
public class ScreenshotCurrentViewport {
public static void main(String[] args) {
// Optional: Setup WebDriver using WebDriverManager
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com"; // Example URL
try {
driver.get(url);
driver.manage().window().maximize(); // Maximize for better view (optional)
// 1. Cast WebDriver to TakesScreenshot
TakesScreenshot ts = (TakesScreenshot) driver;
// 2. Get the screenshot as a File
File sourceFile = ts.getScreenshotAs(OutputType.FILE);
// 3. Define the destination file path
File destinationFile = new File("screenshots/current_viewport_" + System.currentTimeMillis() + ".png");
// 4. Copy the source file to the destination
FileUtils.copyFile(sourceFile, destinationFile);
System.out.println("Screenshot taken and saved to: " + destinationFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error taking screenshot: " + e.getMessage());
e.printStackTrace();
} finally {
if (driver != null) {
driver.quit();
}
}
}
}
Explanation:
TakesScreenshot ts = (TakesScreenshot) driver;: You cast yourWebDriverinstance to theTakesScreenshotinterface, asWebDriveritself doesn't directly expose screenshot methods.ts.getScreenshotAs(OutputType.FILE);: This is the core method.OutputType.FILE: Specifies that the screenshot should be returned as ajava.io.Fileobject.OutputType.BYTES: Returns the screenshot as a byte array (useful if you want to store it in a database or send it over a network without saving to disk first).OutputType.BASE64: Returns the screenshot as a Base64 encoded string (useful for embedding in HTML reports).
FileUtils.copyFile(sourceFile, destinationFile);: Copies the temporary screenshot file generated by Selenium to your desired location.FileUtilsmakes this very easy.System.currentTimeMillis(): Used to generate a unique filename, preventing overwriting previous screenshots.
2. Capture a Specific Web Element
This allows you to take a screenshot of only a particular HTML element on the page.
Java
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ScreenshotSpecificElement {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
String url = "https://www.google.com"; // Example URL
try {
driver.get(url);
driver.manage().window().maximize();
// Find the element you want to screenshot (e.g., the Google search button)
WebElement searchButton = driver.findElement(By.name("btnK")); // Or By.id, By.cssSelector, etc.
// Get the screenshot of the element
File sourceFile = searchButton.getScreenshotAs(OutputType.FILE);
// Define the destination file path
File destinationFile = new File("screenshots/element_screenshot_" + System.currentTimeMillis() + ".png");
// Copy the source file to the destination
FileUtils.copyFile(sourceFile, destinationFile);
System.out.println("Element screenshot taken and saved to: " + destinationFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error taking element screenshot: " + e.getMessage());
e.printStackTrace();
} finally {
if (driver != null) {
driver.quit();
}
}
}
}
Explanation:
WebElement searchButton = driver.findElement(By.name("btnK"));: First, you locate the desired web element using any of theBystrategies (id, name, className, cssSelector, xpath, linkText, partialLinkText, tagName).searchButton.getScreenshotAs(OutputType.FILE);: TheWebElementinterface also provides thegetScreenshotAs()method, allowing you to directly capture its image.
3. Capture Full Page (Scrollable Content)
This is more nuanced and browser-dependent.
Firefox (GeckoDriver): Firefox's GeckoDriver in Selenium 4+ offers a direct method for full-page screenshots.
Other Browsers (Chrome, Edge, etc.): For browsers like Chrome and Edge, Selenium's standard API does not natively provide a
getFullPageScreenshotAs()method that captures the entire scrollable content without external logic. You typically need to:Execute JavaScript: Scroll the page, take multiple viewport screenshots, and then programmatically stitch them together using an image processing library (like
java.awt.imageor a third-party library). This is complex.Use Browser-Specific Extensions/Capabilities: Some headless browser modes or browser developer tools might have built-in full-page screenshot capabilities that you could potentially invoke via Selenium's
executeCdpCommandfor Chrome DevTools Protocol.
Full Page Screenshot for Firefox (Selenium 4+)
Java
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions; // For setting options if needed
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ScreenshotFullPageFirefox {
public static void main(String[] args) {
// Setup GeckoDriver using WebDriverManager
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
String url = "https://www.selenium.dev/"; // A page with scrollable content
try {
driver.get(url);
driver.manage().window().maximize(); // Maximize window for full page visibility
// Cast to FirefoxDriver to access getFullPageScreenshotAs
// This method is specific to FirefoxDriver
File sourceFile = ((FirefoxDriver) driver).getFullPageScreenshotAs(OutputType.FILE);
File destinationFile = new File("screenshots/full_page_firefox_" + System.currentTimeMillis() + ".png");
FileUtils.copyFile(sourceFile, destinationFile);
System.out.println("Full page screenshot (Firefox) taken and saved to: " + destinationFile.getAbsolutePath());
} catch (IOException e) {
System.err.println("Error taking full page screenshot for Firefox: " + e.getMessage());
e.printStackTrace();
} finally {
if (driver != null) {
driver.quit();
}
}
}
}
Note on Chrome/Edge Full Page Screenshots:
If you need a full-page screenshot for Chrome or Edge, and the getFullPageScreenshotAs() method isn't available or suitable, you'd typically implement a custom solution involving JavaScript. This often looks like:
Get the total scroll height of the page.
Get the viewport height.
Loop:
Scroll the page by one viewport height.
Take a screenshot of the visible area.
Store the screenshot.
Repeat until the end of the page.
Stitch all the individual screenshots together into one large image.
This process is quite involved and goes beyond a simple Selenium command. Libraries like AShot for Java are sometimes used for this purpose, but they also rely on internal logic to achieve full-page captures.
Important Considerations:
Error Handling: Always wrap your screenshot logic in
try-catchblocks to handleIOException(for file operations) andNoSuchElementException(if an element is not found for element screenshots).File Paths:
new File("screenshots/..."): This assumes ascreenshotsfolder exists in your project's root directory. If not, it will be created. You can also specify an absolute path (e.g.,"C:/screenshots/..."or"/Users/YourUser/screenshots/...").System.currentTimeMillis(): Essential for unique filenames to avoid overwriting.
OutputType: Choose the appropriate output type (FILE,BYTES,BASE64) based on how you intend to use the screenshot data.Waiting for Page Load: Ensure the page is fully loaded and stable before taking a screenshot. Use explicit waits (
WebDriverWait) for elements orThread.sleep()(less ideal) if necessary.Maximize Window: Maximizing the browser window (
driver.manage().window().maximize();) before taking a viewport screenshot can ensure you capture as much content as possible.
These examples provide a solid foundation for taking screenshots in Selenium with Java.