Bene Bene - 1 year ago 114
Python Question

Cannot select an option from drop down menu Python Selenium

I am relatively new to Python (well, more than relatively). I need to select an option from a drop down menu. I have tried almost all the solutions available. But nothing seems to work.
This is the page I am interacting with:
And this is the part of the page source that is giving me problems:

<select id="criteriaSidesLeg" name="leg" style="display:none;" aria-disabled="false">

<option title="2014 - 2019" value="8">2014 - 2019</option>

<option title="2009 - 2014" value="7" selected="selected">2009 - 2014</option>

<option title="2004 - 2009" value="6">2004 - 2009</option>

<option title="1999 - 2004" value="5">1999 - 2004</option>


what I have tried up to now is:

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from import Select
from import WebDriverWait
from import expected_conditions as EC
from import By
# pressing the botton year menu making the element visible
year= driver.find_element_by_id('criteriaSidesLeg')
for option in year.find_elements_by_tag_name('option'):
if option.text=='2009 - 2014':

this gives me this error:

selenium.common.exceptions.ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated
(Session info: chrome=54.0.2840.87)
(Driver info: chromedriver=2.25.426935 (820a95b0b81d33e42712f9198c215f703412e1a1),platform=Mac OS X 10.10.5 x86_64)

I have tried also this other solution

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.ID,"criteriaSidesLeg")))
select = Select(element)

this is not giving me error but this TimeOutexception

raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:

So I also tried to execute this command line:

driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].value == arguments[1]){ select.options[i].selected = true; } }", element, "01")

But again getting the aforementioned Timeout exception
how to proceed ?
I hope that the question is clear enough and thank you all in advance!

Answer Source

You're trying to handle wrong element. Try this code and let me know in case of any issues:

driver.find_element_by_xpath('//a[text()="2009 - 2014"]').click()

Same without using XPath:

driver.find_element_by_link_text('2009 - 2014').click()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download