Getting next element in Selenium

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.

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)