通过此链接 https://bancadatistatisticaoas.inail.it/analytics/saw.dll?Dashboard&PortalPath=%2Fshared%2FBDS%2F_portal%2FINF_Definiti_Industria_e_Servizi 我需要单击“F Costruzioni”,然后单击 F 41 COSTRUZIONI ED埃迪菲西。这是我的代码,但它不起作用。我做错了什么?
# Initialize the WebDriver
driver = webdriver.Chrome(options=chrome_options) driver.maximize_window()
try:
# Navigate to the page
driver.get(
"https://bancadatistatisticaoas.inail.it/analytics/saw.dll?Dashboard&PortalPath=%2Fshared%2FBDS%2F_portal%2FINF_Definiti_Industria_e_Servizi"
)
wait = WebDriverWait(driver, 90)
# f_costruzioni_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='F COSTRUZIONI']")))
# f_costruzioni_button.click()
wait.until(EC.element_to_be_clickable((By.XPATH, "//table/tbody/tr/td[text()='F COSTRUZIONI']"))).click()
# This is a simple sleep; for a more robust solution, check the download directory for a new file
import time
time.sleep(10)
finally:
# Clean up by closing the browser
driver.quit()
你的代码的问题在于,你试图点击包含文本的表格单元格(td 元素)本身,而不是它内部的链接。你需要定位到链接元素,然后点击它。
以下修改后的代码应该可以工作:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# 初始化 WebDriver
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
try:
# 导航到页面
driver.get(
"https://bancadatistatisticaoas.inail.it/analytics/saw.dll?Dashboard&PortalPath=%2Fshared%2FBDS%2F_portal%2FINF_Definiti_Industria_e_Servizi"
)
wait = WebDriverWait(driver, 90)
# 等待 F COSTRUZIONI 链接可点击,并点击
f_costruzioni_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//td[text()='F COSTRUZIONI']/a")))
f_costruzioni_link.click()
# 等待 F 41 COSTRUZIONI ED EDIFICI 链接可点击,并点击
f_41_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//td[text()='F 41 COSTRUZIONI ED EDIFICI']/a")))
f_41_link.click()
# 等待页面加载完成
time.sleep(10)
finally:
# 关闭浏览器
driver.quit()
这段代码做了以下几件事:
-
使用
//td[text()='F COSTRUZIONI']/a
定位到包含文本 "F COSTRUZIONI" 的表格单元格内的链接元素。 - 点击该链接。
-
使用
//td[text()='F 41 COSTRUZIONI ED EDIFICI']/a
定位到包含文本 "F 41 COSTRUZIONI ED EDIFICI" 的表格单元格内的链接元素。 - 点击该链接。
这应该可以解决你的问题。如果你还有其他问题,请随时提问。
标签:python,selenium-webdriver From: 78772948