简体   繁体   English

使用Selenium和python进行依赖的DROP-DOWN选择

[英]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. 我有一个包含两个下拉菜单(分别为A和B)的表单。下拉菜单B的内容取决于下拉菜单A的选择。

The form uses AJAX to load the contents of drop down B. 该表单使用AJAX加载下拉菜单B的内容。

I am using selenium and python to automatically select the drop down. 我正在使用selenium和python自动选择下拉列表。 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. 我可以选择下拉菜单A,但是由于使用了AJAX,我的代码无法选择下拉菜单B的内容。

I have searched the selenium documentation (Explicit wait) and some stackoverflow answers but still I am unable to implement it in python. 我已经搜索了硒文档(显式等待)和一些stackoverflow答案,但仍然无法在python中实现它。 I am a newbie in python and selenium so please bear me. 我是python和硒的新手,所以请多多包涵。

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. 建议一些逻辑,直到整个下拉列表B被加载。

You can use the options attribute from Select to check you have elements in the dropdown 您可以使用该选项的属性Select要检查你在下拉菜单元素

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: 您尚未共享这些不同菜单的html外观,所以让我假定下拉菜单B由具有特定类甚至更好的ID的DIV包装,也许是:

<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. 经过大量搜索之后,我找到了一个简单的解决方案,可以在其中选择下拉列表B的内容。因此,我在回答自己的问题。

Use sleep function from time module to pause the execution of the program for some time(in seconds). 使用time模块中的sleep功能可以暂停程序执行一段时间(以秒为单位)。

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. 它现在正在运作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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