Reputation: 782
I have multiple select option as:
<select id="auto_year" class="element" onchange="loadMakes(this.value);" name="auto_year">
<option value="0000">- Year -</option>
<option value="2014">2014</option>
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
</select>
<select id="auto_make" class="element" onchange="loadModels(document.getElementById('auto_year').value, this.value);;" name="auto_year">
<option value="0000">- Make-</option>
</select>
Initially, the option inside the select id = "auto_make" is empty. But as i select one of the option from the select id ="auto_year", the option appears. I'm facing problem in selecting values. My code is :
from selenium import webdriver
from bs4 import BeautifulSoup
import re
browser = webdriver.Firefox()
browser.get(certain_url)
html_source = browser.page_source
yearoption_val = browser.find_element_by_id('auto_year')
for yearoption in yearoption_val.find_elements_by_tag_name('option'):
if yearoption.text == '- Year -':
continue
else:
yearoption.click()
itemmake_val = browser.find_element_by_id('auto_make')
for itemmake in itemmake_val.find_elements_by_tag_name('option'):
if (itemmake.text == r'\- Make \(\d+ items\) \-' or '- Model -'):
continue
else:
itemmake.click()
The problem with the code is it selects 2014 and moves into 2013 without looking for option in id = auto_make for 2014. Any help or suggestions would be really helpful.
Upvotes: 0
Views: 961
Reputation: 271
I was struggling with the same problem 2 weeks ago. I tried a number of different options and ended up with the method below. The issue was click()
or Select()
did make the selection but failed to set the value. The only thing you might be missing is sending a key to the select object.
from selenium.webdriver.common.keys import Keys
def select_option_from_a_dropdown(self, select_object, option_value):
"""
To select options in "<select>" in selenium we need to select the option first and then need
to send ENTER key on the select.
"""
options = select_object.find_elements_by_tag_name("option")
for option in options:
self.log.info(option.text)
if option.text.upper() == option_value.upper():
option.click()
select_object.send_keys(Keys.RETURN)
If you are facing the same problem as I did, you just need to perform yearoption_val.send_keys(Keys.RETURN)
after yearoption.click()
.
**English is not my first language. Please edit the answer as appropriate
Upvotes: 1
Reputation: 3428
Have you tried instantiating a Select object? Here is an example from the Selenium site in Python;
# available since 2.12
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_tag_name("select"))
select.deselect_all()
select.select_by_visible_text("Edam")
Upvotes: 1