版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013003827/article/details/86355242
首先,我们看一下,什么是select下拉选择框, 如下图所示:
上述HTMLDemo源码:
<html>
<body>
<form>
<h2 >select下拉选择框练习</h2>
<h4>选择你想学的编程语言</h1>
<select name="basicjs" >
<option value="01">Java</option>
<option value="02">C++</option>
<option value="03">Python</option>
<option value="04">JavaScript</option>
</select>
</form>
</body>
</html>
有了select下拉选项框,那么我们该如何去定位里面的选项呢?
- 方法1: 先定位到select框,再定位框中的选项 (二次定位 )
- 方法2: 直接定位选项
- 方法3: 采用selenium中的Select模块来直接定位
注意: 要定位select,必须导入select库 : from selenium.webdriver.support.select import Select
下面以定位select下拉选项中的 “python” 为例,分别采用上面三种方法来定位。
【方法1: 代码】
# coding=utf-8
from selenium import webdriver
import os
import time
from selenium.webdriver.support.select import Select #导入Select类库
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('selectdemo.html')
driver.get(file_path)
time.sleep(3)
s = driver.find_element_by_name("basicjs") # 先定位select框
time.sleep(1)
s.find_element_by_xpath("//option[@value='03']").click() # 再定位选项
# 上面两句可以合并成一句,如下
#driver.find_element_by_name("basicjs").find_element_by_xpath("//option[@value='03']").click()
【方法2: 代码】
# coding=utf-8
from selenium import webdriver
import os
import time
from selenium.webdriver.support.select import Select #导入Select类库
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('selectdemo.html')
driver.get(file_path)
time.sleep(3)
driver.find_element_by_xpath("//*[@name='basicjs']/option[3]").click()
【方法3: 代码】
这里有多种方法可以定位,
- (1)是通过select选项的索引来定位;
- (2)是通过select选项的value值来定位
- (3)通过文本内容来定位
# coding=utf-8
from selenium import webdriver
import os
import time
from selenium.webdriver.support.select import Select #导入Select类库
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('selectdemo.html')
driver.get(file_path)
time.sleep(3)
s = driver.find_element_by_name("basicjs") #先定位select框
#Select(s).select_by_index(2) # 通过select选项的索引来定位,索引是从0开始的
#Select(s).select_by_value("03") # 通过select选项的value值来定位
Select(s).select_by_visible_text("Python") # 通过选项的文本内容来定位
time.sleep(2)
说明:
Select类提供了三种选择某一选项的方法:
- select_by_index(index) # index是从0开始计数的
- select_by_value(value) # value是option标签的一个属性,并不是显示在下拉框中的值
- select_by_visible_text(text) # text是option标签中的值,是显示在下拉框中的值
Select类既然提供了选择的方法,自然的,也会有相应的反选的方法,如下:
- deselect_by_index(index)
- deselect_by_value(value)
- deselect_by_visible_text(text)
- deselect_all() # 取消全部
前三种分别与 select
相对应,第四种是全部取消选择。有一种特殊的select标签,即设置了multiple=”multiple”
属性的select
,这种select框是可以多选的,你可以通过多次select,选择多项选项,而通过deselect_all()
来将他们全部取消。