I'm adding web tests to my project using Selenium. I already have a bunch of tests that check for a specific element using:
final WebElement dateElement = web.findElement(By.id(elementId));
And this works fine. Now I have another requirement. This is in my generated page:
<input type="text" id="dateElement" name="dateElement" value="bunch of monkeys" tabindex="101" placeholder="yyyy-mm-dd">
<span class="error">dateElement is an invalid date</span>
How can I get hold of the error message? I'd like something that allows me to request the span element with class "error" that is just after dateElement.
(This error message was ganerated by Spring MVC, so it's not easy to change it directly. Possible I guess, but I'd prefer not).
Any alternative idea is welcome.
We can find a next sibling element from the same parent in Selenium webdriver. This is achieved with the help of xpath locator. It is important to note that it is only possible to traverse from current sibling to the next sibling with the help of xpath.
The findElement(By. xpath) method is used to identify an element which matches with the xpath locator passed as a parameter to this method. The findElements(By. xpath) method is used to identify a collection of elements which match with xpath locator passed as a parameter to that method.
OK, I already found a solution using Xpath and following-sibling, it wasn't too complicated.
final WebElement errorElement = web.findElement(By.xpath("//*[@id='" + elementId + "']/following-sibling::span[@class='error']"));
This gives me what I wanted, and throws a NoSuchElementException
when it's not here, which is exactly what I want.
elementSelector = "input + span[class='error']";
final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));
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