Selenium finding hidden element

Viewed 459

I'm having difficulty accessing a dropdown menu in www.meridiancu.ca. It's the one under "Select Banking Type" on the right side of the homepage. Once I run my code.

from selenium import webdriver
from selenium.webdriver.common import action_chains, keys
import time


driver = webdriver.Chrome()
driver.maximize_window()
driver.get("http://www.meridiancu.ca")

bank_type = driver.find_element_by_id('SelectAccount')
bank_type.click()

I get the following output, and I'm not sure how I can find this "hidden" element.

DevTools listening on ws://127.0.0.1:12015/devtools/browser/6f5fba77-4c41-49b9-93a3-64a8363cd35b
Traceback (most recent call last):
  File "C:\Users\Imad\Documents\Programming\Python\dropdown select.py", line 14, in <module>
    bank_type.click()
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 80, in click
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 501, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 308, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: element not visible
  (Session info: chrome=62.0.3202.94)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.16299 x86_64)

Any suggestions or solutions would be greatly appreciated.

3 Answers

The issue you're encountering is that your selector is finding 2 elements that match. The first element that matches is hidden. The hidden element is displayed when the page is viewed by a mobile browser.

I did some investigating, and found that the following CSS selector will find the element you are looking for.

bank_type = find_element_by_css_selector('.show-for-large select#SelectAccount.banking-target')

The following code for working with select tag:

from selenium.webdriver.support import ui


ui.Select(driver.find_element_by_css_selector(".sign-in-panel.sign-in-banner #SelectAccount")).select_by_visible_text("Small Business Banking")

Result: The "Small Business Banking" option should be selected from the dropdown.

Hope it helps you!

You can also do the iteration over all options in the drop down, using the following code snippet.

el = driver.find_element_by_id('SelectAccount')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'Personal Banking':
        option.click() # select() in earlier versions of webdriver
        break
Related