getScreenshotAs for WebElement was not supported until Selenium 3.x, so we had to take a long route like taking a complete viewable area screenshot and then cropping the part where we have our element by using getLocation, getSize, getWidth, getHeight and then finally getSubimage method like shown in image 1.
But from Selenium 4 (at least alpha 3) onwards, getScreenshotAs is also supported for WebElement like this:
public static void eleScreenshot() throws InterruptedException, IOException {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://in.linkedin.com/");
if(driver instanceof ChromeDriver)
{
File src = driver.findElement(By.xpath("/html/body/nav/a[1]/li-icon")).getScreenshotAs(OutputType.FILE);
FileHandler.copy(src, new File("D:\\Learning_Automation\\Practise\\Image1.png"));
}
}
Note* I used instanceof method as I was getting some other driver incompatibility error but it should work without even instanceof method.
seleniumautomation selenium4 screenshot automationtesting testing
1) Using Java (Lengthy way) : Create a utility and use it:>> import java.io.BufferedOutputStream; import org.openqa.selenium.io.Zip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipUtil { private static final int BUFFER_SIZE = 4096; public void unzip (String zipFilePath, String destDirectory) throws IOException { File destDir = new File(destDirectory); if (!destDir.exists()) { destDir.mkdir(); } ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); ZipEntry entry = zipIn.getNextEntry(); // to iterates over entries in the zip folder while (entry != null) { String filePath = destDirectory + File.separator + entry.getName(); if (!entry.isDirectory()) { extractFile (zipIn, filePath);
Comments
Post a Comment