Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next element in Selenium

I'm looking for a generic way to get the next element within Selenium. Jquery has a .next() function and overloads to allow a given type so I imagine there may be a JS based solution available for Selenium.

Given it's such a useful feature I'd have imagined someone must have done it already by now.

Cheers, Jamie

like image 347
Jamie Avatar asked Aug 09 '13 17:08

Jamie


People also ask

How can I get next sibling in XPath?

WebElement parent = child. findElement(By. xpath(".."));

How would you get to the next sibling in Java?

To get the immediate next sibling element of given web element using Selenium for Java, find element on the given web element by XPath with the XPath expression as "following-sibling::*" .

How do you get siblings in Selenium?

To get all the sibling elements of a given web element using Selenium for Java, Find the following elements on the given web element by XPath with the XPath expression as "following-sibling::*" . Find the preceding elements on the given web element by XPath with the XPath expression as "preceding-sibling::*" .

What is xOffset and yOffset in Selenium?

Both xOffset and yOffset represent the relative pixel distance (integer) with which to scroll. For xOffset , positive value means to scroll right, and negative value means to scroll left. For yOffset , positive value means to scroll downward, and negative value means to scroll upward.


2 Answers

I'm going to assume you mean when you select an element some selector (say By.className("primary")), and you want to get the next item that has that class name?

To do that, you need to call driver.findElements(By.className("primary")). This will give you a list of all of the elements that match that selector. Then, you can pick whichever one suits your needs.

If however, next() actually returns the next sibling, then you can do it these ways:

  • Javascript: element.nextSibling()
  • CSS : element + *
  • Xpath: element/following-sibling::*

(Replace element with your selector)

like image 64
Nathan Merrill Avatar answered Oct 19 '22 11:10

Nathan Merrill


One of the possible ways to navigate to element under same hierarchy is to use /../ in xpath as shown below:

current_element = driver.find_element_by_xpath('//android.widget.RelativeLayout/android.widget.TextView[@text="Current element text"]/../android.widget.TextView[@text="Next element text"]')

Here it will:

  1. Firstly navigate to android.widget.TextView[@text = "Current element text"]
  2. Then it will go back to parent element i.e android.widget.RelativeLayout and select the next android.widget.TextView[@text="Next element text"] under the same hierarchy.
like image 32
Parth Naik Avatar answered Oct 19 '22 11:10

Parth Naik