Search code examples
pythonseleniummenudropdown

selecting from dropdown menu with selenium


Im trying to select a dropdown with selenium in python. I cant get it working. I have tried "clicking" on different links via the xpath and it works. But I can't figure out the drop down menu.

This is the code I have tried using:

path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(path)

driver.get("http://elpris.dk")

driver.find_element_by_xpath("""//*[@id="btnSelectProfile"]""").click()

Solution

  • The webpage is written using Angular JS, which loads data dynamically. So, use WebDriverWait so that the page gets loaded properly.

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    
    path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
    
    driver = webdriver.Chrome(path)
    driver.get("http://elpris.dk")
    delay = 15
    wait = WebDriverWait(driver, delay)
    try:
        elem = wait.until(
               EC.element_to_be_clickable((By.ID, 'btnSelectProfile')))
        elem.click()
    except Exception as e:
        print(e)        
    

    Another option is to add some sleep to wait for the data to get loaded properly like below:

    import time
    path = r"C:\Program Files\chromedriver_win32\chromedriver.exe"
    driver = webdriver.Chrome(path)
    
    driver.get("http://elpris.dk")
    time.sleep(3)
    driver.find_element_by_xpath("""//*[@id="btnSelectProfile"]""").click()
    

    Then the click will work.