繁体   English   中英

Python + Selenium -- 无法点击元素

[英]Python + Selenium -- Can't click on the element

我的页面上有一个用于订单搜索结果的下拉菜单:

<ul class="chzn-results" style="overflow-x: hidden;">
    <li id="selZB4_chzn_o_0" class="active-result result-selected" style=""> by popular </li>
    <li id="selZB4_chzn_o_1" class="active-result" style=""> price (from cheap) </li>
    <li id="selZB4_chzn_o_2" class="active-result" style=""> price (from expensive) </li>
    <li id="selZB4_chzn_o_3" class="active-result result-last" style=""> discount </li>
</ul>

我点击了打开这个下拉菜单:

action = ActionChains(driver)
order = driver.find_element_by_xpath('/html/body/div[2]/div[1]/div/div[5]/div[2]/div[3]/div/div/div[2]/div[2]/span[2]/span[1]')
action.move_to_element(order).click().perform()

下拉菜单打开。 接下来,我想选择“从便宜”来订购页面上的对象,但 Selenium 返回 AttributeError: 'list' object has no attribute 'id'。

我尝试了不同的方法,例如:

from_cheap = driver.find_elements_by_xpath("//[@id="selZB4_chzn_o_1"]")
action.move_to_element(from_cheap).click().perform()

或通过 CSS 选择器。 或通过 id,但它仍然没有点击。 我的错误是什么?

所需的元素是一个动态元素,因此要找到该元素,您必须诱导WebDriverWait使该元素可点击,您可以使用以下任一解决方案:

  • XPATH 1

     WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='chzn-results']//li[@class='active-result' and contains(., 'from cheap')]"))).click()
  • XPATH 2

     WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='chzn-results']//li[@class='active-result' and normalize-space()='price (from cheap)']"))).click()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM