簡體   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