Selenium: How do I get the src of an image? Selenium: How do I get the src of an image? selenium selenium

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


Assuming that you have an image in a WebElement (lets say img), in Java world you can retrieve the link below

Editing the answer to clarify.By Java world I mean Selenium 2.0 Java bindings. In Selenium 2.0 (of course if you are using webdriver) has a class called WebElement representing elements on the page. getAttribute is a selenium Method in Java binding.

String url = "http://www.my.website.com";WebDriver driver = new FirefoxDriver();driver.get(url);WebElement img = driver.findElement(By.id("foo"));String src = img.getAttribute("src");

Perhaps there is something similar in PHPUnit


Below code will help you to get the list of all images and their URLs.You can also use script instead on img to get the list of javascript files.

    package seleniumlinkpackage;    import java.util.List;    import org.openqa.selenium.By;    import org.openqa.selenium.WebDriver;    import org.openqa.selenium.WebElement;    import org.openqa.selenium.firefox.FirefoxDriver;    public class xmenfirstclass {    public static void main(String[] args) throws InterruptedException {        String url = "Paste Your URL here";        WebDriver driver = new FirefoxDriver();        driver.get(url);        List links=driver.findElements(By.tagName("img"));    // this will display list of all images exist on page        for(WebElement ele:links){            System.out.println(ele.getAttribute("src"));        }            //Wait for 5 Sec            Thread.sleep(5);            // Close the driver            driver.quit();        }    }


You can use 'getAttribute' with XPath to get an image src (or any other attribute: alt, title, width, etc.)

selenium.getAttribute("//img/@src");