How I can select previous element in Selenium based of condition after?


I have a bellow HTML:

<div class="row">
  <div><span class="checkbox"></span></div>
  <a title="something"></div>
<div class="row">
  <div><span class="checkbox"></span></div>
  <a title="somethingelse"></div>

I would like to click on the checkbox if the a’s title is something. I do not know how many rows are there so I need to check every row and if there the title == ‘something’ click the previous checkbox.

I tried to implement this in Python and Selenium, but so far could not succeed. I can check for a like:

driver.find_element_by_xpath(f"//div[contains(@class, 'row')]//a[@title='something']")

But how I can select the previous element?

Does anybody have a recommendation?


I am using get_attribute and trying to extract title and then putting a if clause that if title attribute text matches with your expected string then click on the above check box.

try this :

actual_text = driver.find_element_by_xpath(f"//div[contains(@class, 'row')]//a[@title='something']")
if actual_text.get_attribute('title') == 'your expected string here':
    driver.find_element(By.XPATH, "//div[contains(@class, 'row')]//a[@title='something']/../child::span")

Answered By – cruisepandey

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published