How to find the src of an image in Selenium java?
Last Updated :
03 Oct, 2024
Selenium WebDriver is a popular automation tool used for testing web applications across different browsers. One common task in web automation is extracting information from web elements, such as retrieving the src attribute of an image. The src attribute holds the URL of the image, and Selenium provides a simple way to extract this attribute using Java.
In this guide, we will walk through the steps to get the src of an image in Selenium Java, ensuring you can easily access the image URLs on a webpage for your automation tasks.
Different ways to find the src of the image
We will be trying to find the source of the image in the following webpage which has the HTML as follows:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
span{
color: red;
}
body {
margin: 0;
font-size: 18px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
min-height: 100vh;
text-align: center;
}
</style>
</head>
<body>
<h2>My favourite cars in <span>red</span></h2>
<img src="https://images.classic.com/vehicles/1e7a53d12e8e002e84ff7d861f0e1a9f23597219.JPG?w=1200&h=676&fit=crop" width="420px" alt="Ferrari Testarossa">
<img src="https://www.carscoops.com/wp-content/uploads/2021/02/Lamborghini-Countach.jpg" width="420px" alt="Lamborghini Countach">
<p>Made for GeeksForGeeks</p>
<a href="https://github.com/globbertrot/images">Source Code</a>
</body>
</html>
We can see that there are two images in the webpage and to find the source of the images we will be using following Java code
Java
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class App {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe"); //replcae the Path of the chrome driver
WebDriver driver = new ChromeDriver();
driver.get("https://globbertrot.github.io/images");
try {
WebElement image = driver.findElement(By.tagName("img"));
System.out.println(image.getAttribute("src"));
} catch (NoSuchElementException e) {}
driver.quit();
}
}
Explanation
- Firstly, we create a WebDriver object which visits our website containing the two images.
- We are finding a web element inside the webpage using findElement() method of the driver boject.
- Inside the findElement() method we specify the driver to find the element by tag name (HTML tags) i.e. img.
- Once we have found the image element, we can use getAttribute() method of WebElement object which takes the attribute name as argument and returns the value associated with the particular attribute of the HTML element.
However, the above code will only work for one image and will return the source of the first image found in the entire webpage. If the webpage contains multiple images like in this case our website contains 2 images, we have to use findElements() method which will return list of elements based on the criteria.
Java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class App {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://globbertrot.github.io/images");
try {
List<WebElement> listOfImages = driver.findElements(By.tagName("img"));
for(WebElement image: listOfImages){
System.out.println(image.getAttribute("src"));
}
} catch (NoSuchElementException e) {}
driver.quit();
}
}
Explanation
- We have created a driver object and visited our website which contains the images.
- This time we have used findElements() method of driver object which takes the element identifier as argument (in this case we are identifying the elements based on tag name).
- The above method returns the list of elements matching our criteria meaning it will contain all the images present in our webpage.
- Then we will iterate through the list and print out the source attribute individually for all image present inside the list.
- Also, in case there are no images present in the website, we are catching the NoSuchElementException which is thrown if the driver is unable to find elements matching our criteria.
Instead of finding elements by their tag name, we can also find elements based upon their class name, id name, xpath or css selectors which makes it flexible and easy to select specific images from the entire webpage.
driver.findElement(By.className("image-class")); // Selects element having class attribute equal to "image-class"
driver.findElement(By.id("image-id")); // Selects element having id attribute equal to "image-id"
driver.findElement(By.xpath("//img[2]")); // Selects second image from the webpage
driver.findElement(By.cssSelector("#image-id")); // Selects element having id attribute equal to "image-id"
Output
Conclusion
By using Selenium WebDriver in Java, you can easily get the src of an image on any webpage, which is especially useful for validating images or extracting URLs during automation. Simply use the getAttribute("src")
method on an image element, and Selenium will return the image's URL.
This process simplifies web scraping and testing when dealing with images on a site. For reliable automation, always ensure your Selenium setup is correctly configured with the latest drivers using WebDriverManager.
Similar Reads
How to click on an image using Selenium in Java? Selenium, a popular tool for automating web application testing across browsers, often requires image interaction. In this article we will discuss how to clicking on image using Selenium in Java.PrerequisitesJava Development Kit (JDK) installed.Selenium WebDriver library added to your project.A supp
3 min read
How to Handle iframe in Selenium with Java? In this article, we are going to discuss how to handle the iframe in Selenium with Java. The following 6 points will be discussed.Table of ContentWhat are iframes in Selenium?Difference between frame and iframe in SeleniumSteps to Identify a Frame on a Page?How to Switch Over the Elements in iframes
11 min read
How to disable images in chrome using Selenium java? Disabling images in Chrome during automated testing can enhance performance and speed up your Selenium tests. This is particularly useful when dealing with large web pages or when you want to focus on specific elements without the distraction of images. In this guide, we'll walk you through how to d
2 min read
How to upload a file in Selenium java with no text box? Uploading a file in Selenium Java without a visible text box can be easily handled using the sendKeys() method. Even if the file input field is hidden or styled as a button, Selenium allows you to interact with it by providing the file path directly. This method simplifies the process of file upload
3 min read
How to download File in Selenium Using java Automating the file download process is essential in web automation testing, especially for validating functionalities involving document downloads such as PDFs, images, or CSV files. However, Selenium WebDriver doesnât directly handle file downloads. To overcome this limitation, we can configure th
2 min read