- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to save a canvas as PNG in Selenium?
We can save a canvas as png in Selenium. We shall first identify the canvas with the help of any locators like xpath, css, and so on. Then obtain the value of src attribute with the getAttribute method.
We shall build an URL in java with the class URL and have a BufferedImage via ImageIOclass. Then utilize the same class to save the canvas with the png extension in a location.
Let us try to save the below image within the project folder.
Example
Code Implementation.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; public class SaveCanvas{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/index.htm"); // identify canvas WebElement l = driver.findElement(By.xpath("//img[@title='Tutorialspoint']")); // get src value of element String v = l.getAttribute("src"); // creating URL URL i = new URL(v); //having BufferedImage with ImageIO class BufferedImage s = ImageIO.read(i); // save image in location with .png extension ImageIO.write(s, "png", new File("Logo.png")); driver.close(); } }
Output
Logo.png file gets created within the project folder.
Advertisements