How do I get the src of an image in Selenium?

We can get the source of an image in Selenium. An image in an html document has <img> tagname. Each image also has an attribute src which contains the source of image in the page.

To fetch any attribute in Selenium, we have to use the getAttribute() method. The method takes the attribute name as a parameter. So to get the src attribute, we have to write getAttribute("src").


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class Imagesrc{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "";
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify image
      WebElement l =driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));
      //getAttribute() to get src of image
      System.out.println("Src attribute is: "+ l.getAttribute("src"));