首先,将下面html代码保存到一个文件中

后续的代码小案例都是访问此html的<!DOCTYPE html>

  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <title>下拉框</title>
  5. </head>
  6. <body>
  7. <select id="pro">
  8. <option value="gd">广东</option>
  9. <option value="hb">湖北</option>
  10. <option value="gj">北京</option>
  11. </select>
  12. <select id="city" multiple>
  13. <option value="gz">广州</option>
  14. <option value="wh">武汉</option>
  15. <option value="gj">北京</option>
  16. </select>
  17. </body>
  18. </html>

注意

若select下拉框有 multiple 属性,则可以多选option,但这种情况不常见

关于下拉框的操作

  • 返回所有选项
  • 返回所有被选中的选项
  • 通过value属性选中or取消选中选项
  • 通过index索引选中or取消选中选项
  • 通过标签间文本选中or取消选中选项
  • 取消选中所有选项

返回选项&选中操作

  1. # !/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. __title__ =
  5. __Time__ = 2020/3/25 17:52
  6. __Author__ = 小菠萝测试笔记
  7. __Blog__ = https://www.cnblogs.com/poloyy/
  8. """
  9. from time import sleep
  10. from selenium.webdriver.support.select import Select
  11. from selenium import webdriver
  12. driver = webdriver.Chrome("../resources/chromedriver.exe")
  13. # 将html文件更改为自己的路径
  14. driver.get("file:///C:/下拉框.html")
  15. driver.maximize_window()
  16. # 找到select标签元素
  17. pro = Select(driver.find_element_by_id("pro"))
  18. # 返回所有选项
  19. for option in pro.options:
  20. print(option.text)
  21. # 返回所有被选中的选项
  22. for option in pro.all_selected_options:
  23. print(option.text)
  24. # 通过value选中
  25. pro.select_by_value("bj")
  26. sleep(1)
  27. # 通过index选中
  28. pro.select_by_index(1)
  29. sleep(1)
  30. # 通过标签文本选中
  31. pro.select_by_visible_text("广东")

取消选中操作

  1. # 找到id=city的下拉框
  2. city = Select(driver.find_element_by_id("city"))
  3. # 全选
  4. for option in city.options:
  5. if not option.is_selected():
  6. city.select_by_visible_text(option.text)
  7. sleep(1)
  8. # 根据value取消选中
  9. city.deselect_by_value("bj")
  10. sleep(1)
  11. # 根据index取消选中
  12. city.deselect_by_index(0)
  13. sleep(1)
  14. # 根据标签文本选中
  15. city.deselect_by_visible_text("武汉")
  16. sleep(1)
  17. # 全选
  18. for option in city.options:
  19. if not option.is_selected():
  20. city.select_by_visible_text(option.text)
  21. sleep(1)
  22. # 取消选中所有选项
  23. city.deselect_all()

知识点

取消操作只适用于添加了multiple的下拉框,否则会报错

  1. raise NotImplementedError("You may only deselect options of a multi-select")
  2. NotImplementedError: You may only deselect options of a multi-select

Select源码解读

  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. """

知识点