单击Selenium Webdriver的下拉元素菜单

时间:2012-09-12 19:46:12

标签: 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变量不是菜单本身,它是菜单元素的跨度之一,doc是点击Perfil html元素以显示下拉列表。

编辑2:

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

最终修改:

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

2 个答案:

答案 0 :(得分:8)

为什么不选择这样的选项

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调用来填充你的列表,你实际上并不需要执行点击。

答案 1 :(得分:0)

您需要找到目标的链接。您没有真正点击元素,单击链接...(或者更确切地说,您单击其中包含链接的元素)。话虽这么说,点击链接的最可靠的方法是隔离链接元素。

frame = driver.find_element_by_id('this_is_your_frame_name') 
links = frame.find_elements_by_xpath('.//a')
links[1].click()

或者,

for link in links:
    if link.text() == "Administratar Permisos":
        link.click()
相关问题