Search code examples
pythonseleniumdropdown

how to select an item of a dropdown using selenium in python


I'm trying to click on "Universität Bern" which is an option of a dropdown that can be found in the following link:

I used the following code to get to the page (link), but I'm not able to click on an opetion of this dropdown. My code is :

     import content as content
     from selenium import webdriver
     from selenium.webdriver.support.ui import Select
     import time

     path = "C:\Program Files\chromedriver.exe"
     driver = webdriver.Chrome(path)
     driver.get("https://www.zssw.unibe.ch/usp/zms/angebot/6728/index_ger.html")
     pathanmelden = driver.find_element_by_xpath("//* 
     [@id='content']/section/div/div/div/div/div/table/tbody/tr[5]/td[2]/a")
     pathanmelden.click()
     time.sleep(1)
     pathforstudents = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/form/input")
     pathforstudents.click()
     chosetheuniversity = driver.find_element_by_class_name("")# This is what does not work"

I appreciate any help.


Solution

  • This drop down is not build using select and option tag so select class won't work.

    You should first click on drop down arrow and then click on the desired element.

    Code:

    driver.maximize_window()
    wait = WebDriverWait(driver, 30)
    
    driver.get("https://www.zssw.unibe.ch/usp/zms/angebot/6728/index_ger.html")
    pathanmelden = driver.find_element_by_xpath("//* [@id='content']/section/div/div/div/div/div/table/tbody/tr[5]/td[2]/a")
    pathanmelden.click()
    time.sleep(1)
    pathforstudents = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/form/input")
    pathforstudents.click()
    
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "img#user_idp_iddicon"))).click()
    time.sleep(2)
    wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@title='Universities: Universität Bern']"))).click()
    

    Imports:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

    PS: I have not changed your existing locators, you can change them as well since they are absolute xpath. time.sleep(2) is just for visualization purposes. You can remove that once you test out the code.