web自动化测试第12步:selenium中下拉框的解决方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/CCGGAAG/article/details/76694707

在之前,遇到下拉框的时候我们可以用两次点击来选择我们需要的选项,不过对于下拉框,我们的webdriver中有封装的Select包单独对于下拉框有一套处理的方法,我们可以来学习一下,然后在测试的时候根据不同的情况来选择需要哪儿种方法。

1.select包方法的使用示例以及定位方式

 select方法示例

select下拉框的定位

 

 

2.select包内的方法详解

1.获取option元素

options:获取包含select下拉框内所有option项element的列表

all_selected_options: 获取当前选中项element的列表

first_selected_option:获取所有下拉选项中的第一个选项的element(或者获取当前选中的这一项)

 

2.选择option

select_by_value(values):选择option标签中value属性为:values的选项

select_by_index(index_number):选择索引为index_number的选项(索引从0开始)

select_by_visible_text(text):选择option选项内容为:text的选项

 

3.复选select的情况(select标签中,multiple="multiple"时,即可多选的select选择框)

deselect_all: 取消所有已选择的选项

deselect_by_value(values):取消选择option标签中value属性为:values的选项

deselect_by_index(index_number):取消选择索引为index_number的选项(索引从0开始)

deselect_by_visible_text(text):取消选择option选项内容为:text的选项

 

3.实例验证(一)百度贴吧高级搜索下拉框

百度贴吧高级搜索

本条实例主要是获取选项元素和通过方法来选择某项option,代码如下

 


 
 
  1. from selenium import webdriver
  2. from selenium.webdriver.support.ui import Select
  3. from time import sleep
  4. # 打开Chrome浏览器
  5. driver = webdriver.Chrome()
  6. # 进入百度高级搜索页
  7. driver.get( "http://tieba.baidu.com/f/search/adv")
  8. # 获取select下拉框的元素
  9. ele_select = driver.find_element_by_css_selector( "select[name='sm']")
  10. # 获取下拉框中所有选项元素(element)
  11. options = Select(ele_select).options
  12. print( "所有选项元素的列表:%s" % options)
  13. for i in options:
  14. print( "元素对应的选项:%s"% i.text)
  15. # 获取下拉框当前显示(选中)的元素(element)
  16. options_selected = Select(ele_select).all_selected_options
  17. print( "-----------------------分隔符---------------------------")
  18. print(options_selected)
  19. for j in options_selected:
  20. print( "当前选中的选项(默认项):%s" % j.text)
  21. # 选择value值为2的选项
  22. Select(ele_select).select_by_value( "2")
  23. sleep( 1)
  24. # 输出默认项(当前选中项)
  25. now = Select(ele_select).first_selected_option
  26. print(now.text)

 

 

4.实例验证(二):多选multiple选择框

我们把我们自己写的表单信息给写入到页面上,使用菜鸟教程在线代码运行工具生成html页面,然后再进行多选select框的验证实验。

多选框演示


 
 
  1. from selenium import webdriver
  2. from selenium.webdriver.support.ui import Select
  3. from time import sleep
  4. # 打开浏览器,进入演示页面
  5. driver = webdriver.Chrome()
  6. driver.get( "https://www.runoob.com/runcode")
  7. # 定位输入框文本域
  8. ele_textarea = driver.find_element_by_css_selector( "#codeinp")
  9. # 清空文本域
  10. ele_textarea.clear()
  11. # 输入多选下拉框的演示源码 (multiple="multiple\")
  12. texts = "<html> " \
  13. "<body><form><select multiple=\"multiple\" name=\"cars\"><option value=\"volvo\">Volvo</option>" \
  14. "<option value=\"saab\">Saab</option><option value=\"fiat\">Fiat</option>\" \
  15. \"<option value=\"audi\">Audi</option></select></form></body></html>"
  16. ele_textarea.send_keys(texts)
  17. # 点击提交代码
  18. submit_button = driver.find_element_by_css_selector( "#btrun")
  19. submit_button.click()
  20. sleep( 2)
  21. # 定位frame和select元素
  22. all_handles = driver.window_handles
  23. driver.switch_to.window(all_handles[ 1])
  24. ele_select = driver.find_element_by_css_selector( "body > form > select")
  25. # 选择全部的选项(多选)
  26. Select(ele_select).select_by_index( 0)
  27. sleep( 1)
  28. Select(ele_select).select_by_index( 1)
  29. sleep( 1)
  30. Select(ele_select).select_by_index( 2)
  31. sleep( 1)
  32. Select(ele_select).select_by_index( 3)
  33. sleep( 1)
  34. # 取消选择第一项选项(页面上可以观察到变化)
  35. Select(ele_select).deselect_by_index( 0)
  36. # 输出当前选择的第一项
  37. now = Select(ele_select).first_selected_option
  38. print(now.text)


5.源码展示

 


 
 
  1. class Select(object):
  2. def __init__(self, webelement):
  3. """
  4. Constructor. A check is made that the given element is, indeed, a SELECT tag. If it is not,
  5. then an UnexpectedTagNameException is thrown.
  6. :Args:
  7. - webelement - element SELECT element to wrap
  8. Example:
  9. from selenium.webdriver.support.ui import Select \n
  10. Select(driver.find_element_by_tag_name("select")).select_by_index(2)
  11. """
  12. if webelement.tag_name.lower() != "select":
  13. raise UnexpectedTagNameException(
  14. "Select only works on <select> elements, not on <%s>" %
  15. webelement.tag_name)
  16. self._el = webelement
  17. multi = self._el.get_attribute("multiple")
  18. self.is_multiple = multi and multi != "false"
  19. @property
  20. def options(self):
  21. """Returns a list of all options belonging to this select tag"""
  22. return self._el.find_elements(By.TAG_NAME, 'option')
  23. @property
  24. def all_selected_options(self):
  25. """Returns a list of all selected options belonging to this select tag"""
  26. ret = []
  27. for opt in self.options:
  28. if opt.is_selected():
  29. ret.append(opt)
  30. return ret
  31. @property
  32. def first_selected_option(self):
  33. """The first selected option in this select tag (or the currently selected option in a
  34. normal select)"""
  35. for opt in self.options:
  36. if opt.is_selected():
  37. return opt
  38. raise NoSuchElementException("No options are selected")
  39. def select_by_value(self, value):
  40. """Select all options that have a value matching the argument. That is, when given "foo" this
  41. would select an option like:
  42. <option value="foo">Bar </option>
  43. :Args:
  44. - value - The value to match against
  45. throws NoSuchElementException If there is no option with specisied value in SELECT
  46. """
  47. css = "option[value =%s]" % self._escapeString(value)
  48. opts = self._el.find_elements(By.CSS_SELECTOR, css)
  49. matched = False
  50. for opt in opts:
  51. self._setSelected(opt)
  52. if not self.is_multiple:
  53. return
  54. matched = True
  55. if not matched:
  56. raise NoSuchElementException("Cannot locate option with value: %s" % value)
  57. def select_by_index(self, index):
  58. """Select the option at the given index. This is done by examing the "index" attribute of an
  59. element, and not merely by counting.
  60. :Args:
  61. - index - The option at this index will be selected
  62. throws NoSuchElementException If there is no option with specisied index in SELECT
  63. """
  64. match = str(index)
  65. for opt in self.options:
  66. if opt.get_attribute("index") == match:
  67. self._setSelected(opt)
  68. return
  69. raise NoSuchElementException("Could not locate element with index %d" % index)
  70. def select_by_visible_text(self, text):
  71. """Select all options that display text matching the argument. That is, when given "Bar" this
  72. would select an option like:
  73. <option value="foo">Bar </option>
  74. :Args:
  75. - text - The visible text to match against
  76. throws NoSuchElementException If there is no option with specisied text in SELECT
  77. """
  78. xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text)
  79. opts = self._el.find_elements(By.XPATH, xpath)
  80. matched = False
  81. for opt in opts:
  82. self._setSelected(opt)
  83. if not self.is_multiple:
  84. return
  85. matched = True
  86. if len(opts) == 0 and " " in text:
  87. subStringWithoutSpace = self._get_longest_token(text)
  88. if subStringWithoutSpace == "":
  89. candidates = self.options
  90. else:
  91. xpath = ".//option[contains(.,%s)]" % self._escapeString(subStringWithoutSpace)
  92. candidates = self._el.find_elements(By.XPATH, xpath)
  93. for candidate in candidates:
  94. if text == candidate.text:
  95. self._setSelected(candidate)
  96. if not self.is_multiple:
  97. return
  98. matched = True
  99. if not matched:
  100. raise NoSuchElementException("Could not locate element with visible text: %s" % text)
  101. def deselect_all(self):
  102. """Clear all selected entries. This is only valid when the SELECT supports multiple selections.
  103. throws NotImplementedError If the SELECT does not support multiple selections
  104. """
  105. if not self.is_multiple:
  106. raise NotImplementedError("You may only deselect all options of a multi-select")
  107. for opt in self.options:
  108. self._unsetSelected(opt)
  109. def deselect_by_value(self, value):
  110. """Deselect all options that have a value matching the argument. That is, when given "foo" this
  111. would deselect an option like:
  112. <option value="foo">Bar </option>
  113. :Args:
  114. - value - The value to match against
  115. throws NoSuchElementException If there is no option with specisied value in SELECT
  116. """
  117. if not self.is_multiple:
  118. raise NotImplementedError("You may only deselect options of a multi-select")
  119. matched = False
  120. css = "option[value = %s]" % self._escapeString(value)
  121. opts = self._el.find_elements(By.CSS_SELECTOR, css)
  122. for opt in opts:
  123. self._unsetSelected(opt)
  124. matched = True
  125. if not matched:
  126. raise NoSuchElementException("Could not locate element with value: %s" % value)
  127. def deselect_by_index(self, index):
  128. """Deselect the option at the given index. This is done by examing the "index" attribute of an
  129. element, and not merely by counting.
  130. :Args:
  131. - index - The option at this index will be deselected
  132. throws NoSuchElementException If there is no option with specisied index in SELECT
  133. """
  134. if not self.is_multiple:
  135. raise NotImplementedError("You may only deselect options of a multi-select")
  136. for opt in self.options:
  137. if opt.get_attribute("index") == str(index):
  138. self._unsetSelected(opt)
  139. return
  140. raise NoSuchElementException("Could not locate element with index %d" % index)
  141. def deselect_by_visible_text(self, text):
  142. """Deselect all options that display text matching the argument. That is, when given "Bar" this
  143. would deselect an option like:
  144. <option value="foo">Bar </option>
  145. :Args:
  146. - text - The visible text to match against
  147. """
  148. if not self.is_multiple:
  149. raise NotImplementedError("You may only deselect options of a multi-select")
  150. matched = False
  151. xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text)
  152. opts = self._el.find_elements(By.XPATH, xpath)
  153. for opt in opts:
  154. self._unsetSelected(opt)
  155. matched = True
  156. if not matched:
  157. raise NoSuchElementException("Could not locate element with visible text: %s" % text)
  158. def _setSelected(self, option):
  159. if not option.is_selected():
  160. option.click()
  161. def _unsetSelected(self, option):
  162. if option.is_selected():
  163. option.click()
  164. def _escapeString(self, value):
  165. if '"' in value and "'" in value:
  166. substrings = value.split("\"")
  167. result = ["concat("]
  168. for substring in substrings:
  169. result.append("\"%s\"" % substring)
  170. result.append(", '\"', ")
  171. result = result[0:-1]
  172. if value.endswith('"'):
  173. result.append(", '\"'")
  174. return "".join(result) + ")"
  175. if '"' in value:
  176. return "'%s'" % value
  177. return "\"%s\"" % value
  178. def _get_longest_token(self, value):
  179. items = value.split(" ")
  180. longest = ""
  181. for item in items:
  182. if len(item) > len(longest):
  183. longest = item
  184. return longest

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值