十三、下拉框选择

一、下拉选择框的分类和实现

selenium的下拉选择框。我们通常会遇到两种下拉框,一种使用的是html的标签select,另一种是使用input标签做的假下拉框,后者我们通常的处理方式与其他的元素类似,点击或使用JS等。而对于前者,selenium给了有力的支持,就是Select类。

新建select.html页面

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>下拉选择框练习</title>
    </head>
    <body>
        <script>
        function oc(){
            alert(document.f1.t1.value());
        }
        </script>
        <form>
        搜索引擎:
        <select id="s1Id">
            <option></option>
            <option value="o1" id="id1">谷歌搜索</option>
            <option value="o2" id="id2">必应搜狗</option>
            <option value="o3" id="id3">搜狗搜索</option>
            <option value="o4" id="id3">百度搜狗</option>
        </select>
        </form>
    </body>
</html>

二、导入(import)

你可以用以下方式导入:

from selenium.webdriver.support.ui import Select
# 或者直接从select导入
# from selenium.webdriver.support.select import Select

注意:这两种方法没有本质的区别,只是把select import进去。

三、定位下来框

Select类提供了三种选择某一选项的方法:

select_by_index(index)
select_by_value(value)
select_by_visible_text(text)

针对于示例网站中的第一个select框:

<select id="sid">
            <option></option>
            <option value="o1" id="id1">谷歌搜索</option>
            <option value="o2" id="id2">必应搜狗</option>
            <option value="o3" id="id3">搜狗搜狗</option>
            <option value="o4" id="id4">百度搜狗</option>
        </select>

实例代码

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import os

#文件路径生成
file_path = 'file:///' + os.path.abspath('select.html')

driver = webdriver.Chrome()
driver.get(file_path)

s1 = Select(driver.find_element_by_id('sid'))  # 实例化Select

s1.select_by_index(4)  # 选择第二项选项 百度搜狗
s1.select_by_value("o3")  # 选择value="o3"的项 搜狗搜索
s1.select_by_visible_text("谷歌搜索")  # 选择text="谷歌搜索"的值,即在下拉时我们可以看到的文本

driver.quit()

以上是三种选择下拉框的方式,注意:

  1. index从 0 开始
  2. value是option标签的一个属性值,并不是显示在下拉框中的值
  3. visible_text是在option标签中间的值,是显示在下拉框的值

四、反选(deselect)

既然有选择必然可以反选,即取消选择。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()来将他们全部取消。

posted @ 2019-10-24 14:45  酒剑仙*  阅读(510)  评论(0编辑  收藏  举报