如何在python中使用selenium单击<ul>元素中的<li>元素列表?

时间:2016-10-18 00:51:19

标签: python selenium

enter image description here

我尝试在下拉菜单中选择2002。 它在任何晚期都不起作用。 我使用了xpath

driver.find_element_by_xpath("html/body/main/div/form/div[3]/div[1]/section/div[3]/fieldset/div[7]/dl[1]/dd/ul/li[1]/a").click()

但它不起作用..我尝试了所有的解决方案...... 我该如何选择?

2 个答案:

答案 0 :(得分:2)

如果您能够打开下拉项但无法点击项目,则应尝试将Explicit WaitsWebDriverWait一起使用,等待此元素可见并启用如下所示: - < / p>

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

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul#ulBirthYear a[data-value='2002']")))
element.click()

或者

element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "2002")))
element.click()

答案 1 :(得分:0)

首先,尽量避免使用绝对XPATH。 使用这样的东西:

'//ul[@id="uiBirthYear"]/li/a[@data-value="2002"]'

在尝试获取/单击此元素之前,还要确保DOM已完全构建。

尝试设置隐式等待

driver.implicitly_wait(10)

明确等待(了解更多:http://selenium-python.readthedocs.io/waits.html