调用python下拉菜单中的变量

时间:2016-02-17 13:59:44

标签: python python-2.7 selenium selenium-webdriver

我可以通过变量从下拉列表中进行选择吗? E.g。

FROM = "Leeds Bradford"

    # fill out the form
    depart_from = Select(driver.find_element_by_id("ctl00_centralDynamicContent_originatingAirportDropDown"))
    depart_from.select_by_value(FROM)

我知道上面的例子不起作用

2 个答案:

答案 0 :(得分:0)

您可以使用Select class

选择三个选项
depart_from.select_by_value(value)
#
depart_from.select_by_visible_text(text)
#
depart_from.select_by_index(index)
  

修改

有点脏,但你可以试试

# get all the options in the <select>
options = depart_from.options

# find the correct index
int index
for option in range(0, len(options)):
    if options[option].get_attribute(title) == 'LEEDS BRADFORD':
        index = option
        break

# select the option by index
depart_from.select_by_index(index)

答案 1 :(得分:0)

  

From是一个字符串,可在选项标签&gt;中找到title ='LEEDS BRADFORD'现已发布问题

据我了解,您需要按title属性选择选项。这是一个示例:

FROM = "LEEDS BRADFORD"

depart_from = driver.find_element_by_id("ctl00_centralDynamicContent_originatingAirportDropDown")
depart_from.click()

option = depart_from.find_element_by_css_selector('option[title="%s"]' % FROM)
option.click()