How to locate an tag within a webpage using Selenium and Java

前端 未结 4 2029
南笙
南笙 2021-01-26 04:24

I want to locate the image tag in a webpage. The application contains a VIEW ICON. While inspecting the view icon, it is coded as image tag. I am not s

相关标签:
4条回答
  • 2021-01-26 04:52

    <image>

    The <image> SVG element includes images inside SVG documents. It can display raster image files or other SVG files.

    The only image formats SVG software must support are JPEG, PNG and other SVG files. Animated GIF behavior is undefined.

    SVG files displayed with <image> are treated as an image: external resources aren't loaded, :visited styles aren't applied, and they cannot be interactive. To include dynamic SVG elements, try <use> with an external URL. To include SVG files and run scripts inside them, try <object> inside of <foreignObject>.

    Note: The HTML spec defines as a synonym for while parsing HTML. This specific element and its behavior only apply inside SVG documents or inline SVG.


    This usecase

    As the <image> element is a SVG element so to locate such elements you have to explicitly specify the SVG namespace when accessing the elements using xpath as follows:

    • For <svg> elements:

      //*[name()="svg"]
      
    • For <g> elements:

      //*[name()="svg"]/*[name()="g"]
      
    • For <image> elements:

      //*[name()="svg"]/*[name()="image"]
      

    References

    You can find a couple of relevant detailed discussions in:

    • How to access to 'rect' type element through Selenium-Python
    • How to click on SVG elements using XPath and Selenium WebDriver through Java
    • Unable to locate SVG elements through xpath on Kendo UI chart
    0 讨论(0)
  • 2021-01-26 04:59

    Can you please execute the code below and let me know what you get. System.out.println(driver.findElements(By.tagName(“image”)).size());

    if you still get null pointer exception , there is something wrong with your driver object . This code should return 0 if no image tag found on page , else the number of image tags on that page

    Depending on the number of image tags , you can decide on the index of image tag you want to click , and then execute click on that element

    0 讨论(0)
  • 2021-01-26 05:02

    You image doesn't have the "user-view-icon" CSS class assigned and XPath doesn't work.

    you could do:

    WebElement image = driver.findElement(By.cssSelector("svg.user-dropdown-icon > image"));
    
    0 讨论(0)
  • 2021-01-26 05:04

    Try this:

    Selenium - Java

    /*get element by tag name*/
    WebElement image = driver.findElement(By.tagName("image")); 
    

    If there are more than one image on the page , use

    /*get all elements by tag name*/
    List<WebElement> images = driver.findElements(By.tagName("image")); 
    

    from the list above determine which one do you want to use(tip : use a foreach loop to iterate)

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