Examples
Screenshot of a particular element with Java and Selenium
Add Selenium to your Maven project
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.34.0</version>
</dependency> selenium-java 4.11+ includes Selenium Manager, which downloads the right chromedriver automatically. Check Maven Central for the latest version.
Take a screenshot of the element and save to file
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
public class Screenshot {
public static void main(String[] args) throws Exception {
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless=new");
ChromeDriver driver = new ChromeDriver(options);
driver.get("https://www.htmltoimage.com/demo");
WebElement element = driver.findElement(By.cssSelector("#example-card"));
File image = element.getScreenshotAs(OutputType.FILE);
Files.copy(image.toPath(), Path.of("element.png"));
driver.quit();
}
} Find out how to take a full-page screenshot with Java and Selenium.
That was 25 lines of code — plus a browser to run in production
Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:
curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com" Try the Urlbox screenshot API — free trial, no browser babysitting.