Select下拉框操作

1、认识Select框,

  • 平时遇到下图中的情况,通过下拉列表选择的信息
  • select的标签属性:<select class="form-control" id="corporationName" style="margin-bottom:4px;" name="corporationName" data-bv-field="corporationName">
  • 存在两个选项值:<option value="函数兔008集团" selected="">函数兔008集团</option>、<option value="金石基金测试0314日注册">金石基金测试0314日注册</option>

2、定位方法-二次定位

  • 先定位select框,在定位select的选项:查看该代码,id和name都有重复的,不方便定位,选择了xpath定位方法
  • 代码如下:
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://djuat.dtfunds.com/fund-jsqyweb/index.html")
time.sleep(2)
driver.maximize_window()
driver.find_element_by_name("mobile").send_keys("13770506771")
time.sleep(1)
select = driver.find_element_by_xpath("//select")
time.sleep(1)
#先定位select,再操作选项,
select.find_element_by_xpath("//select/option[2]").click()
time.sleep(1)
select.find_element_by_xpath("//select/option[1]").click()
time.sleep(1)

#也可以直接操作,
driver.find_element_by_xpath("//select").find_element_by_xpath("//select/option[2]").click()
time.sleep(1)
driver.quit()

3、定位方法-直接定位

  • 直接通过xpath定位到元素直接操作:driver.find_element_by_xpath("//select/option[2]").click()

4、Select模块-index

  • selenium还提供了更高级的玩法,导入select模块直接用索引来定位
  • 先导入:from selenium.webdriver.support.select impot  Select
  • 然后通过索引来选择对应的选项(index从0开始)
  • 代码:
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time

driver = webdriver.Chrome()
driver.get("http://djuat.dtfunds.com/fund-jsqyweb/index.html")
time.sleep(2)
driver.maximize_window()
driver.find_element_by_name("mobile").send_keys("13770506771")
time.sleep(1)
select = driver.find_element_by_xpath("//select")
#通过索引来定位
Select(select).select_by_index(1)
time.sleep(1)
Select(select).select_by_index(0)
time.sleep(1)
Select(select).select_by_index(1)
time.sleep(1)
driver.quit()

5、Select模块-value

  • 除了使用index方法定位,还有通过value值来定位
  • 代码:
select = driver.find_element_by_xpath("//select")
Select(select).select_by_value("函数兔008集团")
time.sleep(1)
Select(select).select_by_value("金石基金测试0314日注册")
time.sleep(1)
Select(select).select_by_value("函数兔008集团")

6、Select模块-text

  • 除了使用index方法定位,还有通过text值来定位
  • 代码:
#通过text来定位
Select(select).select_by_visible_text("函数兔008集团")
time.sleep(1)
Select(select).select_by_visible_text("金石基金测试0314日注册")
time.sleep(1)
Select(select).select_by_visible_text("函数兔008集团")

7、Select模块-其他方法

  • 除了使用index方法定位,还有通过text值来定位
  • 以下方法没有使用过
deselect_all() :取消所有选项
deselect_by_index() :取消对应 index 选项
deselect_by_value() :取消对应 value 选项
deselect_by_visible_text() :取消对应文本选项
first_selected_option() :返回第一个选项
all_selected_options() :返回所有的选项
原文地址:https://www.cnblogs.com/ygzy/p/9564233.html