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
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
Use CSS selectors instead:
List<WebElement> elements = webDriver.findElements(By.cssSelector("*[attributeName='value']"));
Edit: CSS selectors instead of XPath
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']");
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']"))