Python硒|如何使用index,复杂的下拉结构

时间:2019-04-17 04:05:34

标签: python python-2.7 selenium selenium-webdriver dropdown

我正在使用python硒,我想从主屏幕上显示的下拉列表中获取所有值,下拉值是动态的,基于另一个下拉选择

我尝试了以下代码

try:
    element = find_element_by_locator(self, locator_type, locator)
    print " -- Drop Down available values :"
    for option in element.find_elements_by_tag_name('option'):
        print " -- ", option.text
        if option.text in select_text_option:
            option.click()
except TimeoutException:
    ex_message = " ** failed to get drop down value for " , select_text_option
    print ex_message
    raise Exception(ex_message)

我得到空值作为输出:

<select chosendataplaceholder="Choose Finance Product" class="chosen-select-width" error_target_sel="#evo_lead_evo_finance_product_id_err" name="evo_lead_evo_finance_product_id" data-placeholder="Choose Finance Product" style="display: none;">
  <option selected="" value="1">Novated Finance Lease - Allowed</option>
  <option value="2">Finance Lease - Not Allowed</option>
  <option value="3">Novated Operating Lease - Not Allowed</option>
  <option value="7">Chattel Mortgage - Not Allowed</option>
  <option value="9">Consumer Loan - Not Allowed</option>
  <option value="10">Associate Lease - Not Allowed</option>
  <option value="11">No Finance (Car Only) - Not Allowed</option>
</select>

我想从代码中的下拉列表中获取所有可用值,以便执行一些逻辑功能以发送下一个下拉值,请帮忙

3 个答案:

答案 0 :(得分:0)

处理<select>下拉菜单的正确方法是使用Select

element = find_element_by_name('evo_lead_evo_finance_product_id')
select = Select(element)

# select an option by text
select.select_by_visible_text(select_text_option)

# get all options text
for option in select.options:
    print " -- ", option.text

答案 1 :(得分:0)

虽然可以在我的系统中运行,但您可以尝试使用xpath代替标记名:

List<UserData> list = List();
 var isLoading = false;

void fetchData() async {
setState(() {
  isLoading = true;
});
final response = await get("https://jsonplaceholder.typicode.com/photos");
if (response.statusCode == 200) {
  list = (json.decode(response.body) as List)
      .map((data) => UserData.fromJson(data))
      .toList();
  setState(() {
    isLoading = false;
  });
} else {
  throw Exception('Failed to load photos');
}
}

希望这会有所帮助。

答案 2 :(得分:-1)

要获取所有选项的文本,请使用以下代码:

listele = driver.find_element_by_xpath("//*[@name='evo_lead_evo_finance_product_id']/option")

for i  in range(len(listele)):
    print(listele[i].text)