在Python中使用Selenium来单击href按钮



我正在使用selenium和python来自动化web任务。我已经尝试使用多种不同的功能来尝试点击我需要的按钮:

<a href="/crm/tab/Reports">Reports</a>
.find_element_by_link_text("Reports").click()
.find_element_by_id
.find_element_by_name
.find_element_by_class_name
.find_element_by_css_selector

似乎不能使这项工作,任何建议都将不胜感激。

使用"find_elements_by_xpath"。右键单击并从浏览器中复制XPATH。

使用显式等待可以潜在地解决问题。对于显式等待,您可以使用ID或XPATH。我更喜欢使用XPATH。要获取XPATH,请右键单击元素,单击Inspect,右键单击<a href="/crm/tab/Reports">Reports</a>并选择Copy然后Copy XPATH。现在我们有了XPATH,请执行以下操作:

button_xpath = "the xpath of your element"
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, button_xpath))).click()

上面的代码将等待长达10秒,直到找到按钮元素。如果找不到元素,则会给出TimeoutException。

以下进口是必要的:

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

最新更新