无法单击ul标签下的li元素

时间:2017-05-22 18:52:30

标签: python selenium selenium-webdriver

我有以下HTML代码:

<div class="resultDiv">
<span class="">Sort by : </span>
<div class="dropdown num-record">
<button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="jsSortTypeText">Relevant</span>
<i class="icon-arrows_down"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dLabel" style="display: none;">
<li class="jsSortType" data-value="Prem" data-label="VIP first">VIP first</li>
<li class="jsSortType" data-value="Rec" data-label="Recent">Recent</li>
<li class="jsSortType jsDefaultSort selected" data-value="Rel" data-label="Relevant">Relevant</li>
</ul>
</div>
</div>

我试图点击“dLabel”或“ul”元素,然后点击“最近”选项。

我曾尝试使用动作链,xpath,css选择器,但没有任何效果。使用动作链时,测试运行时没有任何错误,但点击不会发生。

有人可以指导我做错了。我的代码运行没有任何错误,但没有打开下拉列表并选择“最近”选项。

        menu1 = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath(".//*[@id='dLabel']"))
        clickon = WebDriverWait(driver, 20).until(lambda driver: driver.find_element_by_xpath("html/body/div[2]/div[2]/div[6]/div/div[3]/div[3]/div[1]/div/ul/li[2]"))
        action = ActionChains(driver)
        action.move_to_element(menu1).perform()
        action.move_to_element(clickon)
        action.click(clickon)
        action.perform()

我甚至尝试过使用类似下面的内容:

    #now find Documents link and click
    recent = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "Recent")))
    recent.click()

然后我收到超时错误。也许我正在使用组合错误或其他东西。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用预期条件visibility_of_element_located,如下所示:

driver.find_element_by_xpath("//div[@class='resultDiv']/div[@class='dropdown num-record']/button[@id='dLabel']")).click()
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class='resultDiv']/div[@class='dropdown num-record']/ul[@aria-labelledby='dLabel']/li[text()='Recent']')))
driver.find_element_by_xpath("//div[@class='resultDiv']/div[@class='dropdown num-record']/ul[@aria-labelledby='dLabel']/li[text()='Recent']").click()

UPDATE1:尝试以下:

driver.find_element_by_xpath("//div[@class='resultDiv']/div[@class='dropdown num-record']/button[@id='dLabel']")).click()
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.XPATH, '//div[@class='resultDiv']/descendant::li[text()='Recent']')))
driver.find_element_by_xpath("//div[@class='resultDiv']/descendant::li[text()='Recent']").click()

如果你仍然面临这个问题,请告诉我。