Selenium:如何验证下拉列表中当前选择的选项?
Selenium: How can I verify the currently selected option in a dropdown?
我有一个下拉菜单,其中包含多个可供选择的对象:
我想验证 2 小时的默认 select 选项。到目前为止,我已经完成了以下操作:
def time_span_default(self):
dropdown = Select(self.driver.find_element(*Elements.timespan_dropdown))
default_option = dropdown.first_selected_option
return default_option.text
# If default_option.text == "2 hours" my testcase is verified and can continue...
不过,我还想验证其他对象的文本,一旦它们被我 select编辑。
如果我想验证 当前 selected 对象 的文本,谁能告诉我最好的方法是什么?
在您的示例代码中,您设置了 dropdown = Select...
那个 select 对象有一个属性 options
,这将为您提供下拉菜单中每个选项的元素列表,您可以迭代该列表并获取您的元素文本验证
在您的情况下,dropdown.options
将 return 包含 4 个网络元素的列表,每个时间跨度一个。
如果您通过 css_selector 查找 <option>
,您可以通过
获取所选的
selected = self.driver.find_element_by_css_selector("option[selected]")
即使您更改了所选选项,first_selected_option
也应该可以完成这项工作。来自docs
The first selected option in this select tag (or the currently selected option in a normal select)
我有一个下拉菜单,其中包含多个可供选择的对象:
我想验证 2 小时的默认 select 选项。到目前为止,我已经完成了以下操作:
def time_span_default(self):
dropdown = Select(self.driver.find_element(*Elements.timespan_dropdown))
default_option = dropdown.first_selected_option
return default_option.text
# If default_option.text == "2 hours" my testcase is verified and can continue...
不过,我还想验证其他对象的文本,一旦它们被我 select编辑。
如果我想验证 当前 selected 对象 的文本,谁能告诉我最好的方法是什么?
在您的示例代码中,您设置了 dropdown = Select...
那个 select 对象有一个属性 options
,这将为您提供下拉菜单中每个选项的元素列表,您可以迭代该列表并获取您的元素文本验证
在您的情况下,dropdown.options
将 return 包含 4 个网络元素的列表,每个时间跨度一个。
如果您通过 css_selector 查找 <option>
,您可以通过
selected = self.driver.find_element_by_css_selector("option[selected]")
first_selected_option
也应该可以完成这项工作。来自docs
The first selected option in this select tag (or the currently selected option in a normal select)