I am working on Selenium framework 2.0 Web driver and I would like to get value from a span which has a attribute like data-automation-id. The HTML code is as below
<span data-automation-id="SEL_ERR">
Error Description
</span>
Now I want to read the text with in span that has a attribute data-automation-id set to SEL_ERR.
Can some one help me in fixing the code as I have already tried the one below but in vain.
driver.findElement(By.tagName("span")).getAttribute("data-automation-id");
It's simple, really. You are currently getting the very first span
in the entire document.
How do you know if that is the one you want?
Meet, .findElements()
. Instead of getting the very first element that meets a locator, it will give you a list of every element that meets a criteria.
You've not shared much of the HTML, so I don't know if this is a unique element or not.
However, you have two approaches to this:
1) Use .findElements
to get all the span
element's and then filter it down to the elements that specifically have the attribute data-automation-id
with a value of SEL_ERR
or (recommended):
2) Use .findElement
with a selector that specifically targets the element talked about in 1)...if Selenium cannot find it, with a much more targeted selector, then you know it doesn't exist.
driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));
or:
3) A modification of 2). If Selenium cannot find it, it'll throw an exception. Exceptions are costly. You can use .findElements
instead (mentioned in 1)), which will simply return an empty list if it cannot find the element you are looking for:
driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;
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