是否有机会单击上一个找到的同级来打开那里的链接?
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()
不适用于此...
网站结构:
<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>
是否有机会单击上一个找到的同级来打开那里的链接?
看起来问题已经发生,因为
preceding-sibling
的使用不正确。
为了工作,你应该链接两个选择器
find_user = wait.until(EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{cell_vz}')]//preceding-sibling::*[2]")))
我为您的案例创建了示例,当使用
id=2
单击所需元素时,会使用 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()
如果仍然不起作用,可能还有其他原因导致您无法点击。
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
cell = sht.cell(row=2, column=1).value
print(cell_vz)
driver = webdriver.Firefox()
driver.get("https://carkulka.okholding.cz")
username = driver.find_element(By.ID, "UserName")
username.send_keys("username")
password = driver.find_element(By.ID, "Password")
password.send_keys("password")
username.send_keys(Keys.RETURN)
time.sleep(15)
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)
driver.quit()