How to click on a previously found sibling - python selenium

56 views Asked by At

Is there any chance to click on the previous found sibling to open the link that is there?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By  
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import time
import openpyxl



# Load Excel data
excel_data = openpyxl.load_workbook("C:\Automatizace\data.xlsx")
sht = excel_data.active
cell_vz = sht.cell(row=2, column=2).value


try:
   wait = WebDriverWait(driver, 20)
   find_user = wait.until(EC.presence_of_element_located((By.XPATH, f"//*[contains(text(),     '{cell_vz}')]")))


   previous_sibling = find_user.find_element(By.XPATH, "preceding-sibling::*[2]")
   previous_sibling.click()
   print("Najito: ", previous_sibling.text)



except Exception as error:
    print("Chyba při hledání uživatele:", error)

time.sleep(10)

previous_sibling.click() doesn't work for this...

website structure:

 <tr>
    <td>
      <a href="something">text</a>
    </td>
    <td></td> //this is what I need to click on
    <td></td>
    <td></td> //data from cell_vz
    <td></td>
    <td></td>
    <td></td>
    </tr>

Is there any chance to click on the previous found sibling to open the link that is there?

1

There are 1 answers

8
Yaroslavm On

Looks like the issue is happened, because of incorrect usage of preceding-sibling. To make in work, you should chain two selectors

find_user = wait.until(EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{cell_vz}')]//preceding-sibling::*[2]")))

I created example for your case, when clicking on needed element with id=2 triggers background color change on element with id=1

driver.get("https://inputnum.w3spaces.com/saved-from-Tryit-2023-08-17-a93u0.html")

td_2 = driver.find_element(By.XPATH, "//*[@id='1']//preceding-sibling::*[2]")
td_2.click()

If it is still doesn't work, probably, there is another reason why you aren't able to click.