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)?
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.
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].
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(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With