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

前端 未结 9 999
抹茶落季
抹茶落季 2020-12-17 09:32

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, whe

相关标签:
9条回答
  • 2020-12-17 09:58

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

    selenium.getAttribute("//img/@src");
    
    0 讨论(0)
  • 2020-12-17 10:01

    driver.findElement(By.cssSelector("img")).getAttribute("src")

    0 讨论(0)
  • 2020-12-17 10:02

    If You are you using any PHP webdriver like facebook/phpwebdiver, then it will solve your problem very easily.

    Example :

    1) Create a wedriver object:

    public function setUp()
    {
    parent::setUp();
    $web_driver = new WebDriver();
    $element = $web_driver->session();
    }
    

    With this $element variable you can easily access any HTML attribute with the following line:

    $element->element('xpath', '//*[@id="logo"]')->attribute('src');
    

    This will return you the value of src attibute. You can use this line to get any attribute like class, id, title, alt, etc...

    0 讨论(0)
  • 2020-12-17 10:06

    You need to use XPath. For PHPUnit and Selenium the Syntax for getting the src attribute of an image is:

    $imageUrl = $this->getAttribute("//img/@src");
    
    0 讨论(0)
  • 2020-12-17 10:06

    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();
            }
    
        }
    
    
    0 讨论(0)
  • 2020-12-17 10:10

    you have to use

    storeAttribute

    And at the target place u have to mention like this

    //img[@src='imagename.png']@src.

    And store that in a variable lets say

    img

    Now verify that by using

    verifyAttribute

    eg:command:

    verifyAttribute

    target:

    //img[@src='imagename.png']@src

    value:

    ${img}

    0 讨论(0)
提交回复
热议问题