aaa90210
aaa90210

Reputation: 12083

Python Selenium select Bootstrap drop down menu

How do I select an element from a Bootstrap dropdown using Python Selenium? My HTML for the drop down looks something like:

  <select type="select" class="selectpicker form-control" id="selFoo" >
        <option data-hidden="true">Make a selection</option>

        <option>Foo</option>
        <option>Bar</option>
        <option>Baz</option>

  </select>

I have tried using the selenium Select module but get an error like:

selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted 

Upvotes: 0

Views: 2023

Answers (3)

patricmj
patricmj

Reputation: 373

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.select import Select

dropdown = Select(WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_id("selFoo")))
dropdown.select_by_visible_text("Baz")

This should work. If it doesn`t you can try add this before these two lines.

WebDriverWait(driver, 10).until(lambda driver: driver.execute_script("return jQuery.active === 0"))

That will make sure nothing is happening before jQuery is done.

Upvotes: 0

Pabitra Pati
Pabitra Pati

Reputation: 477

You can use the Select module of Selenium. Try the below code piece :-

from selenium import webdriver
from selenium import selenium.webdriver.support.select

dropdown = Select(driver.find_element_by_css_selector(#selFoo))
dropdown.select_by_value('Foo')   # will select Foo option

For more detail refer Select... Hope this helps

Upvotes: 0

aaa90210
aaa90210

Reputation: 12083

If you wanted to select "Bar" from the example drop-down, do something like this:

browser = webdriver.Firefox(profile)
browser.get(hostname)
sleep(1) # wait for page to render    

dropdown = browser.find_element_by_css_selector("button[data-id=selFoo]")
dropdown.click()
sleep(1) # probably not necessary
option   = browser.find_element_by_css_selector("ul[role=menu] a[data-normalized-text='<span class=\"text\">Bar</span>']")
option.click()

Tested in Firefox only.

Upvotes: 1

Related Questions