Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium: find element "next to" other element

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.

like image 774
Guillaume Avatar asked Nov 04 '11 11:11

Guillaume


People also ask

How do you get next element in selenium?

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.

What is find element by xpath in Selenium?

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.


2 Answers

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.

like image 61
Guillaume Avatar answered Oct 11 '22 14:10

Guillaume


elementSelector = "input + span[class='error']";

final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));
like image 34
CBRRacer Avatar answered Oct 11 '22 13:10

CBRRacer