Python+Selenium不能点击elemen

2024-06-17 14:47:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

<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()

下拉菜单打开。接下来,我想选择“from cheap”对页面上的对象进行排序,但Selenium返回AttributeError:'list'对象没有属性'id'。你知道吗

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

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

或CSS选择器。或者通过id,但仍然没有点击。 我错在哪里?你知道吗


Tags: fromdividbystyledriveractionli
1条回答
网友
1楼 · 发布于 2024-06-17 14:47:59

所需的元素是一个动态元素,因此要定位该元素,必须导入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()
    

相关问题 更多 >