Find element by attribute

后端 未结 4 1726
鱼传尺愫
鱼传尺愫 2020-11-30 03:37

I am trying to find an element with Attribute. Well, I can find elements with Id, tagName, Xpath and all other predefined methods in Selenium. But, I am trying to write a me

相关标签:
4条回答
  • 2020-11-30 04:19

    You can easily get this task accomplished with CSS.

    The formula is:

    element[attribute='attribute-value']
    

    So if you have,

    <a href="mysite.com"></a>
    

    You can find it using:

    By.cssSelector("a[href='mysite.com']");
    

    this works using any attribute possible.

    This page here gives good information on how to formulate effective css selectors, and matching their attributes: http://ddavison.io/css/2014/02/18/effective-css-selectors.html

    0 讨论(0)
  • 2020-11-30 04:23

    Use CSS selectors instead:

    List<WebElement> elements = webDriver.findElements(By.cssSelector("*[attributeName='value']"));
    

    Edit: CSS selectors instead of XPath

    0 讨论(0)
  • 2020-11-30 04:23

    As per the documentation:

    By.id Locates elements by the ID attribute. This locator uses the CSS selector *[id='$ID'], not document.getElementById. Where id is the ID to search

    so you can use the below code to search the DOM element with any given attribute as ID and value

    By.id("element[attribute='attribute-value']"); 
    
    0 讨论(0)
  • 2020-11-30 04:28

    I do not understand your requirement:

    Assuming XPath is not an option ...

    If this was just an incorrect assumption on your part, then XPath is the perfect option!

    webDriver.findElements(By.xpath("//element[@attribute='value']"))
    

    Of course you need to replace element, attribute, and value with your actual names. You can also find "any element" by using the wildcard:

    webDriver.findElements(By.xpath("//*[@attribute='value']"))
    
    0 讨论(0)
提交回复
热议问题