python - 使用 Selenium Webdriver 单击下拉元素菜单

标签 python selenium automation webdriver selenium-webdriver

我正在尝试自动执行一项管理任务,到目前为止,我已经让 selenium 单击一个元素以显示下拉菜单。

enter image description here

当需要单击这些菜单元素之一时,我收到一条错误消息,提示必须显示该元素。

代码:

 driver = webdriver.Chrome()
 driver.implicitly_wait(10)
 driver.get(url)
 doc = driver.find_element_by_css_selector('td.ms-vb-title > table')
 try:
    doc.click()
    time.sleep(4)
    menu = driver.find_element_by_xpath('//menu/span[5]')
    time.sleep(4)
    print dir(menu)
    menu.click()
 except:
    traceback.print_exc()
    driver.quit()

错误:

Traceback (most recent call last):
  File "aprobar_docs.py", line 22, in main
    menu.click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 52, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py",
line 205, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l
ine 156, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py"
, line 147, in check_response
    raise exception_class(message, screen, stacktrace)
ElementNotVisibleException: Message: u'Element must be displayed to click'

如您所见,代码等待很多时间才能加载元素。我还尝试将元素的 is_displayed 属性设置为 True 但都没有用。

注意:没有显示的元素是 xpath 搜索中的元素,它存在是因为我用 dir(menu) 记录了它

编辑:

menu 变量不是菜单本身,它是作为菜单元素的 span 之一,docPerfil html 元素点击以显示下拉菜单。

编辑 2:

检查 chrome 工具上的 DOM,当您单击 doc 时,树上会创建一个新菜单,我不知道是因为 ajax 调用还是 vanilla js,我不知道不要认为它的创建方式真的那么重要。我无法从页面中检索它并从中创建一个 python 对象,它至少没有在代码上显示。

最终编辑:

我最终执行了一些 JavaScript 以使其工作。显然,当 Selenium 找到菜单项时,触发菜单下拉的第一个元素失去焦点,它使菜单再次不可见,如果你不选择菜单项并等待一段时间,菜单下拉仍然显示,如果你尝试从菜单中选择一个元素菜单消失。

最佳答案

你为什么不选择这样的选项

el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'The Options I Am Looking For':
        option.click() # select() in earlier versions of webdriver

如果您的点击没有触发 ajax 调用来填充您的列表,您实际上不需要执行点击。

关于python - 使用 Selenium Webdriver 单击下拉元素菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12395228/

相关文章:

python - 使用 Python driver.current_url 语句获取 Selenium Automation 的完整 URL

python - 禁用后如何(重新)启用 tkinter ttk Scale 小部件?

python - 如何提取稀疏矩阵的主对角线?

python - Django 未将图像文件上传到 Azure 存储容器

python - 在 Selenium (Python) 中使用 XPath 选择器 'following-sibling::text()'

apache-flex - Flex Web App 自动化测试

python - 我试图制作一个程序,以便在youtube视频下发送评论,而突然出现sendkeys()问题

python - 如何模拟对 __next__ 的调用

javascript - 如何使用 document.getElementById(someid).onclick 来标记 a

java - EAR 包装自动化