Find next sibling element in Selenium, Python?


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.

To traverse to the next sibling, we have to use the following-sibling concept in xpath. This will allow us to traverse to the next sibling from the present sibling of the same parent.

Syntax −

driver.find_element_by_xpath("//div[@class='txt-bx']/following-sibling::p")

Let us try to move from the first child<h1> of parent <div> to the second <h2> as in the above image.

Example

Code Implementation.

from selenium import webdriver
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
# implicit wait for 5 seconds
driver.implicitly_wait(5)
# maximize with maximize_window()
driver.maximize_window()
driver.get("https://www.tutorialspoint.com/videotutorials/subscription.php")
# identify next sibling element with following-sibling
l=driver.find_element_by_xpath("//h1/following-sibling::h2")
print("Next Sibling Text: " + l.text)
driver.quit()

Output

Updated on: 28-Aug-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements