Home > Net >  Selecting an item from a dropdown list using selenium and request- python
Selecting an item from a dropdown list using selenium and request- python

Time:11-30

I am trying to fill a form up. here is the html for the drop down list

<div class="mb-3">
            <label for="cityId" class="form-label FormLabelsEn">City</label> <label for="cityId" class="form-label float-end">المدينة</label> <select class="form-select citySelect" aria-label="Default select example" id="cityId" required="required"><option value="" selected="" disabled="">اختر من القائمة</option><option value="Ahssa - الأحساء"> Ahssa - الأحساء</option><option value="Ar Rass - الرس"> Ar Rass - الرس</option><option value="Buraidah - بريدة"> Buraidah - بريدة</option><option value="Dammam - الدمام"> Dammam - الدمام</option><option value="Dhahran - الظهران"> Dhahran - الظهران</option><option value="Hafr Albatin - حفر الباطن"> Hafr Albatin - حفر الباطن</option><option value="Jubail - الجبيل"> Jubail - الجبيل</option><option value="KAUST - جامعة الملك عبدالله للعلوم والتقنية"> KAUST - جامعة الملك عبدالله للعلوم والتقنية</option><option value="Khobar - الخبر"> Khobar - الخبر</option><option value="Madina - المدينة المنورة"> Madina - المدينة المنورة</option><option value="Rabigh - رابغ"> Rabigh - رابغ</option><option value="Riyadh - الرياض"> Riyadh - الرياض</option><option value="Tabuk - تبوك"> Tabuk - تبوك</option><option value="Umluj - أملج"> Umluj - أملج</option><option value="Unaizah - عنيزة"> Unaizah - عنيزة</option></select>
        </div>

i am using the below code to click on Riyadh from the drop down list. But I am getting an error

wait = WebDriverWait(driver, 10)

dropdown = wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/form/div[5]/select")))
ActionChains(driver).move_to_element(dropdown).perform()
wait
city = wait.until(EC.visibility_of_element_located((By.XPATH, "/html/body/div[1]/form/div[5]/select/option[5]")))
ActionChains(driver).move_to_element(city).click().perform()

I am getting the following error:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.MoveTargetOutOfBoundsException: Message: move target out of bounds

Can someone please help me with how to click on the drop down.

CodePudding user response:

You can use select class to select an element from drop-down. Like below,

select = Select(driver.find_element_by_id('cityId'))

# select by index
select.select_by_index(1)

import:

from selenium.webdriver.support.ui import Select
  • Related