简体   繁体   中英

Dependent DROP-DOWN selection using selenium and python

I have a form which has two drop-down menu say A and B. Contents of drop-down B is dependent on the selection of drop-down A.

The form uses AJAX to load the contents of drop down B.

I am using selenium and python to automatically select the drop down. I am able to select the drop down A but due to the use of AJAX my code is not working for selecting the content of drop-down B.

I have searched the selenium documentation (Explicit wait) and some stackoverflow answers but still I am unable to implement it in python. I am a newbie in python and selenium so please bear me.

Here is a small portion of my code :

#District selection DROP-DOWN A
district=Select(driver.find_element_by_id("ddlDistrict85"))
district.select_by_value("1")

#SRO selection DROP-DOWN B
# I Need EXPLICIT WAIT logic here to wait till the entire drop-down B is loaded
sro=Select(driver.find_element_by_id("ddlSRO85"))
sro.select_by_value("1")

Suggest some logic to wait till entire drop-down B is loaded.

You can use the options attribute from Select to check you have elements in the dropdown

district=Select(driver.find_element_by_id("ddlDistrict85"))
district.select_by_value("1")

sro=Select(driver.find_element_by_id("ddlSRO85"))
while len(sro.options) == 0:
    continue
sro.select_by_value("1")

You haven't shared what the html looks like for these different menus, so let me assume that drop-down B is wrapped by a DIV with a specific class, or even better an ID, perhaps:

<div id="menuB"> ... </div>

Now, you could use Expected Conditions to wait for that menu to appear.

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.ID,'menuB')))

After searching a lot I found a simple solution where I am able to select the contents of drop-down B. So I am answering my own question.

Use sleep function from time module to pause the execution of the program for some time(in seconds).

The program code would go like this :

import time #To import time module
#District selection
district=Select(driver.find_element_by_id("ddlDistrict85"))
district.select_by_value("1")
#SRO selection
time.sleep(5) 
sro=Select(driver.find_element_by_id("ddlSRO85"))
sro.select_by_value("1")

It's working now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM