Selecting option from dropdown menu using Selenium; Unable to locate element

Viewed 216

I need to select an element from a dropdown list. I'm using Selenium, but I'm having difficulty selecting the dropdown list itself to select from the available options and keep receiving an error "Message: no such element: Unable to locate element:". I've tried the following:

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


driver=webdriver.Chrome()
driver.get('mysite.com')
driver.implicitly_wait(10)
driver.find_element_by_xpath('//*[@id="xpath-example"]').click()
select.select_by_visable_text('option 1')
3 Answers
elem=driver.find_element_by_xpath('//*[@id="xpath-example"]')
sel = Select(elem)

sel.select_by_index(1)
sel.select_by_visible_text("option 1")

You need to find the elem and put it into the Select first of all. Then try one of the two options.

Can you try using by xpath click() action with:

//*[@id="x"]/option[1]

something like: driver.find_element_by_xpath('//*[@id="x"]/option[1]').click()

A couple of things: first, you may want find_elements which returns a list as opposed to find element which returns an object.

Additionally, Because the element which you are trying to access may become visible at an unknown time, you could employ use of a timed wait, which (by your code) would always wait 10 seconds. Or you could make use of the webdriverwait function which would wait only until it was visible (which could be 2,3 or any time up to a timeout which you define)

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome()
driver.get('mysite.com')


try:
    elem = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, '//*[@id="xpath-example"]')))
    item = elem.select_by_visible_text('option 1')
except:
    print("Couldn't find elem")
    pass
Related