Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

image

selenium

I'm using Selenium (within PHPUnit) to test my web application. I would like to test whether a certain image which is present on the page really exists. More precisely, whether the image url returns 404 or not. In order to test that, I need to get the image url. Given the image locator, How do I get the value of its src attribute (its url)?

like image 723
snakile Avatar asked Aug 30 '11 14:08

snakile


People also ask

How do I select an image in Selenium?

We can click on an image with Selenium webdriver in Python using the method click. First of all, we have to identify the image with the help of any of the locators like id, class, name, css, xpath, and so on. An image in the html code is represented by the img tagname. Let us see the html code of an image element.

How do you inspect an image in Selenium?

We can check if an image is displayed on page with Selenium. To verify an image we shall take the help of Javascript Executor. We shall utilize executeScript method to execute the Javascript commands in Selenium. Then pass the command return arguments[0].


2 Answers

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

like image 85
nilesh Avatar answered Oct 20 '22 04:10

nilesh


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();
        }

    }

like image 4
Manish Shukla Avatar answered Oct 20 '22 03:10

Manish Shukla