Selenium Python – Get all the previous sibling elements
In this tutorial, you will learn how to get all the previous sibling elements of a given element, in Selenium Python.
To get all the previous sibling elements of a given element in Selenium Python, call the find_elements() method on the given element and pass By.XPATH
for by parameter, and 'previous-sibling::*
for the value parameter in the function call.
previous-sibling::*
represents all the previous sibling elements for a given element. But it also contains the calling web element. Therefore, we can use Python Slicing technique to remove the first element.
If myelement
is the WebElement object for which we would like to find all the previous sibling elements, the code snippet for find_elements() method is
myelement.find_elements(By.XPATH, "following-sibling::*)
The above method call returns a list of WebElement objects containing the sibling elements previous to the given element.
Example
In this example, we shall use the following HTML file, index.html, that contains a parent div with three children divs.
index.html
<html>
<body>
<h1>Hello Family</h1>
<div id="parent">
<div id="child1">This is child 1.</div>
<div id="child2">This is child 2.</div>
<div id="child3">This is child 3.</div>
<div id="child4">This is child 4.</div>
</div>
</body>
</html>

We shall take the child div div#child3
as our WebElement of interest, find all of its previous sibling elements, and print them to standard output.
Python Program
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
# Setup chrome driver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.set_window_size(500, 400)
# Navigate to the url
driver.get('http://127.0.0.1:5500/index.html')
# Get the div element you are interested in
mydiv = driver.find_element(By.ID, 'child3')
# Get all previous siblings of mydiv
previous_siblings = mydiv.find_elements(By.XPATH, "preceding-sibling::*")
# Print the previous siblings
for sibling in previous_siblings:
print("\nPrevious Sibling")
print(sibling.get_attribute('outerHTML'))
# Close the driver
driver.quit()
Output
Previous Sibling
<div id="child1">This is child 1.</div>
Previous Sibling
<div id="child2">This is child 2.</div>
#child3
has two previous siblings namely, #child1
and #child2
.
Summary
In this Python Selenium tutorial, we have given instructions on how to find all the previous sibling elements of a given web element, with the help of an example program.