首页 > 解决方案 > 无法单击搜索下拉框

问题描述

我正在尝试等待搜索下拉框出现,然后使用以下代码片段在https://amazon.com上单击它。

search_dropdown_box = WebDriverWait(chrome_browser,30).until(EC.visibility_of_element_located((By.ID,"searchDropdownBox")))

然而,尽管如此,代码片段似乎永远不会工作,它总是以失败告终,并出现以下异常。

  File "C:/Users/DHIWAKAR-PC/PycharmProjects/AlationProject/assignment.py", line 18, in <module>
    search_dropdown_box = WebDriverWait(chrome_browser,10).until(EC.visibility_of_element_located((By.ID,"searchDropdownBox")))
  File "C:\Python34\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

我使用预期条件的方式有什么问题,还是我可以利用一些更好的预期条件?

标签: pythonselenium

解决方案


您正在尝试等待一个不可见且不可点击的元素,直到All单击下拉菜单。我的意思是,您尝试单击的定位器在单击All下拉菜单后将变为可见或可单击,并且您在此处使用了错误的定位器。

尝试使用//div[@id='nav-search-dropdown-card']/divas xpath,这样您就可以识别All下拉按钮并可以单击它。

如果要从下拉列表中选择选项,则需要searchDropdownBox在单击All下拉列表后使用 as id。

试试下面的代码:

driver.get('https://www.amazon.com/')
search_dropdown_box = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='nav-search-dropdown-card']/div")))
search_dropdown_box.click()

如果你想在点击后从下拉列表中选择任何选项All,那么你可以使用下面的 python Select

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select

driver = webdriver.Chrome('chromedriver path')
driver.get('https://www.amazon.com/')
search_dropdown_box = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='nav-search-dropdown-card']/div")))
search_dropdown_box.click()

options = driver.find_element_by_id('searchDropdownBox')
select = Select(options)
select.select_by_visible_text('Baby')

我希望它有帮助...


推荐阅读