首页 > 解决方案 > 无法在 python 中使用 selenium 访问 Bootstrap 下拉菜单

问题描述

我的前端有一个下拉菜单,如下所示:

    <div class="dropdown-menu dropdown-menu-right text-left" id="dropdown_menu">
          <a class="dropdown-item" data-toggle="modal" data-target="#exampleModalCenter" id="dropdown_change_pwd">Change Password</a>
          <a class="dropdown-item" href="{{ url_for('auth.logout') }}" id="dropdown_logout">Logout</a>
    </div>

我想在 python 中使用 selenium 访问这些按钮。我试图像这样访问它:

class SearchPage:
_CHANGE_PWD_DROPDOWN = (By.ID, 'dropdown_change_pwd')
_LOGOUT_DROPDOWN = (By.ID, 'dropdown_logout')
_DROPDOWN = (By.ID, 'dropdown_menu')

def __init__(self, browser):
    self.browser = browser

def logout(self):
    time.sleep(5)
    dropdown = self.browser.find_element(*self._DROPDOWN)
    dropdown.click()
    logout = self.browser.find_element(*self._LOGOUT_DROPDOWN)
    logout.click()

但是我总是以:

response = {'status': 400, 'value': '{\n\t"value" : \n\t{\n\t\t"error" : "element not interactable",\n\t\t"message" : "Element is not displayed",\n\t\t"stacktrace" : ""\n\t}\n}\r\n'}

似乎 Selenium 无法处理引导下拉菜单。我怎样才能仍然单击此下拉列表中的任何元素?

如果没有直接的解决方案,是否有解决方法?

标签: pythonseleniumbootstrap-4

解决方案


我的下拉菜单看起来像这样:

    <li class="nav-item">
       <a class="nav-link dropdown-toggle" id="welcome_user" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Welcome, {{ session['current_user']['name'] }}</a>
       <div class="dropdown-menu dropdown-menu-right text-left">
          <a class="dropdown-item" data-toggle="modal" data-target="#exampleModalCenter" id="dropdown_change_pwd">Change Password</a>
          <a class="dropdown-item" href="{{ url_for('auth.logout') }}" id="dropdown_logout">Logout</a>
       </div>
    </li>

首先,我必须通过以下方式访问上部元素:

   dropdown = self.browser.find_elemnt(By.ID, 'welcome_user')
   dropdown.click()

然后我可以访问这样的链接:

    dropdown_logout = self.browser.find_elemnt(By.ID, 'dropdown_logout')
    dropdown_logout.click()

推荐阅读