11、Selenium常用操作之下拉选择框操作
下拉选择框操作
我们在定位页面元素是经常会遇到下拉选择框的操作,如何通过代码模拟选择框选择动作,是本章节需要学习的内容
我们有三种方式能操作下拉选择框
方式一:使用选项标签定位,我们知道,下来选择框标签是select标签和option标签,当页面上只有一个下拉选择框时可以通过tag_name定位选择框和选项,注意,在定位选项之前需要先点击下拉选择框
# 点击下拉选择框 driver.find_element_by_tag_name('select').click() # 点击选择指定选项 driver.find_elements_by_tag_name('option')[3].click()
方式二:使用xpath层级结构定位标签,其实就是使用绝对路径定位选择框和选项
driver.find_element_by_xpath("/html/body/div[4]/select/option[3]").click()
方式三:使用selenium提供的Select模块的方法进行下拉选择框操作
- 需要导包:from selenium.webdriver.support.ui import Select
- 使用格式:Select(定位到的select标签).xxx()
- xxx代表Select类给我们提供的方法和属性
常用方法如下:
- 通过value值定位:select_by_value()
- 通过文本值定位:select_by_visible_text()
- 取消所有选项:deselect_all()
- 通过索引取消指定选项:deselect_by_index()
- 通过value值取消指定选项:deselect_by_value()
- 通过文本取消指定选项:deselect_by_visible_text()
- 返回第一个选项:first_selected_option
1 import time 2 3 from selenium import webdriver 4 from selenium.webdriver.support.ui import Select 5 from selenium.webdriver.support.ui import WebDriverWait 6 from selenium.common.exceptions import TimeoutException 7 from selenium.common.exceptions import NoSuchElementException 8 9 # 获取浏览器驱动 10 driver = webdriver.Chrome() 11 12 # 打开指定网页 13 driver.get('file:///C:/Users/DELL/Desktop/test.html') 14 15 # 浏览器最大化 16 driver.maximize_window() 17 time.sleep(3) 18 19 # 加隐式等待--等待这个爱好选择框加载完成 20 try: 21 hobby_select = WebDriverWait(driver, 10, 1).until(lambda x: x.find_element_by_id('hobby')) 22 print(hobby_select) 23 24 # 获取select操作对象 25 select_option = Select(hobby_select) 26 27 # 选择喝酒和烫头属性 28 # value值定位option 29 # select_option.select_by_value('2') 30 # select_option.select_by_value('3') 31 32 # 通过文本信息定位option 33 # select_option.select_by_visible_text('喝酒') 34 # select_option.select_by_visible_text('烫头') 35 36 # 通过index索引定位option--索引从0开始 37 select_option.select_by_index(1) 38 select_option.select_by_index(2) 39 time.sleep(5) 40 41 # 获取第一个选择的选项 42 first_option = select_option.first_selected_option 43 print(first_option, type(first_option)) 44 45 # 获取所有的选择的内容 46 all_option = select_option.all_selected_options 47 print(all_option, type(all_option)) 48 49 # 取消选择“喝酒的” 50 # select_option.deselect_by_index(1) 51 # select_option.deselect_by_value('2') 52 select_option.deselect_by_visible_text('喝酒') 53 except TimeoutException: 54 print('元素定位超时') 55 except NoSuchElementException: 56 print('元素不存在') 57 58 # 等待5s关闭浏览器 59 time.sleep(8) 60 driver.quit()
浙公网安备 33010602011771号