selenium基础:select下拉框

  我们接着讲selenium元素操作:鼠标操作和select下拉框

select下拉框

做自动化过程中,遇到下拉框的情况还是挺多的,一般分为select类型的下拉框和input类型的假下拉框。

对于input类型的下拉框,处理思路是展开下拉列表,等待选择的元素出现,选择下拉框中的元素。

这篇博客我们只重点讲select类型的下拉框,借助Select类

首先导入Select模块:

1 # coding=utf-8
2 from selenium import webdriver
3 from selenium.webdriver.support.select import Select

1、Select提供了三种选择选项的方法

1 select_by_index          # 通过索引定位
2 select_by_value          # 通过value值定位
3 select_by_visible_text   # 通过文本值定位

注意事项:

index索引是从“0”开始;

value是option标签的一个属性值,并不是显示在下拉框中的值;

visible_text是在option标签中间的值,是显示在下拉框的值;

 

2、Select提供了三种返回options信息的方法

1 options                  # 返回select元素所有的options
2 all_selected_options     # 返回select元素中所有已选中的选项
3 first_selected_options   # 返回select元素中选中的第一个选项

注意事项:

这三种方法的作用是查看已选中的元素是否是自己希望选择的:

options:提供所有选项的元素列表;

all_selected_options:提供所有被选中选项的元素列表;

first_selected_option:提供第一个被选中的选项元素;

 

3、Select提供了四种取消选中项的方法

1 deselect_all             # 取消全部的已选择项
2 deselect_by_index        # 取消已选中的索引项
3 deselect_by_value        # 取消已选中的value值
4 deselect_by_visible_text # 取消已选中的文本值

下面以百度页面为例,点击搜索设置后,设置搜索结果显示为20条

 # coding=utf-8
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.support.select import Select

driver=webdriver.Chrome("D:GoogleChromeApplicationchromedriver")
driver.get('https://www.baidu.com')
#点击搜索设置
time.sleep(5)
driver.find_element_by_xpath('//*[@id="u1"]/a[8]').click()
time.sleep(1)
driver.find_element_by_xpath('//a[text()="搜索设置"]').click()
#等待元素出现
searchset = (By.XPATH, '//li[text()="搜索设置"]')
WebDriverWait(driver, 30, 0.2).until(EC.visibility_of_element_located(searchset))
#实例化Select类
ele=driver.find_element_by_name('NR')
s=Select(ele)
s.select_by_index(1)
#保存设置
driver.find_element_by_xpath('//a[text()="保存设置"]').click()
原文地址:https://www.cnblogs.com/Elaine1/p/10125431.html