kforce kforce - 4 months ago 9
Python Question

Can't access dropdown select using Selenium in Python

I'm new to using Selenium in Python and I'm trying to access index data on Barclays Live's website. Once I login and the page loads, I'm trying to select 'Custom1' from a dropdown in the page. The select object in the HTML code associated with the list looks like this:

<select name="customViewId" class="formtext" onchange="submitFromSelect('username');return false;">
<option value="">&nbsp;</option>
<option value="Favorite Indices">Favorite Indices</option>
<option value="Custom1">Custom1</option>
<option value="CB group">CB group</option>
<option value="Kevin Favorites">Kevin Favorites</option>
<option value="LB Gov/Cdt intermediate">LB Gov/Cdt intermediate</option>
</select>


This is my code up until I try to access this object:

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

#Get chrome driver and connect to Barclays live site
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\chromedriver.exe")
browser.get('https://live.barcap.com/')

#Locate username box and enter username
username = browser.find_element_by_name("user")
username.send_keys("username")

#Locate password box and send password
password = browser.find_element_by_name("password")
password.send_keys("password")

#Click login button
login = browser.find_element_by_id("submit")
login.click()

#Open page where you can select indices
browser.get("https://live.barcap.com/BC/barcaplive?menuCode=MENU_IDX_1061")


I've tried a number of proposed solutions that I've found, usually with the error "Unable to locate element: " followed by whatever method I tried to access the select object with. I don't seem to be able to access it by name, xpath, or by using the Select() function. I've tried putting wait time in the code in case the element hadn't loaded yet, and no luck. Some examples of things I would expect to work, but don't are:

select_box = browser.find_element_by_name("customViewId")
select_box = browser.find_element_by_xpath("//select[option[@value='Custom1']]"


My background isn't in programming, go easy on me if this is a stupid question. Thanks in advance for the help.

Answer

The select element is indeed located in an iframe.

This means that you should switch into the context of the frame and only then find the element:

browser.switch_to.frame("frame_name_or_id")
select_box = browser.find_element_by_name("customViewId")

If you need to get back from the context of the frame, use:

browser.switch_to.default_content()

As for the manipulating the select box part, there is a better way - use the Select class:

from selenium.webdriver.support.select import Select

select_box = Select(browser.find_element_by_name("customViewId"))
select_box.select_by_visible_text("CB group")