Versions used while doing this blog post, (These are the prerequisites to automate chrome browser. Browser and driver versions should match)
selenium-java version – 4.4.0
chrome browser version – 105
chrome driver version – 105 (Download link : https://chromedriver.chromium.org/downloads) [Using WebDriverManager to auto download the correct driver version]
Screenshot of a webelement can be captured using selenium 4 by following below steps:
1. Map the chromedriver using WebDriverManager,
WebDriverManager.chromedriver().setup();
2. Instantiate (creation of object) driver object with ChromeDriver() class (This step opens the chrome browser)
ChromeDriver driver = new ChromeDriver();
3. Now, next steps of maximizing the browser and setting implicit timeout for driver object
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().window().maximize();
4. Launch the expected website URL and observe the offline scenario
driver.get("https://www.google.com");
5. Add an explicit wait that waits till the expected element appears [Note : WebDriverWait(driver object, Duration method) can be used as WebDriverWait(driver object, long) got deprecated now]
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement logo = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[alt='Google']")));
6. Take the screenshot of the element using getScreenshotAs() method and save it to a folder [Note : FileHandler.copy() method can be used to copy between file objects]
File file = logo.getScreenshotAs(OutputType.FILE);
FileHandler.copy(file, new File(System.getProperty("user.dir")+"/src/test/downloads/logo.png"));
Sample code for reference
import io.github.bonigarcia.wdm.WebDriverManager;
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 org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
public class TakeScreenshotOfElementUsingSelenium4 {
public static void main(String[] args) throws IOException {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.manage().window().maximize();
driver.get("https://www.google.com");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement logo = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img[alt='Google']")));
File file = logo.getScreenshotAs(OutputType.FILE);
FileHandler.copy(file, new File(System.getProperty("user.dir")+"/src/test/downloads/logo.png"));
driver.quit();
}
}