场景
在处理下拉框(select)的时候selenium给我们提供了一系列的便捷方法,我们只需要使用selenium.webdriver.support.select.Select类来稍微封装一下就好了。
下面是我们经常会用到的一些方法
- options: 返回下拉框里所有的选项
- all_selected_options: 返回所有选中的选项
- select_by_value(value): 通过option的value值来选择
- select_by_index(index) 通过option的顺序来选择
- select_by_visible_text(text): 通过option的text来选择
代码
s7.html
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <form enctype="multipart/form-data"> <div> <textarea name="meno" >123456</textarea> <select name="city" > <option value="beijing">北京</option> <option value="shanghai">上海</option> <option value="nanjing" selected="selected">南京</option> <option value="chengdu">成都</option> </select> <input type="submit" value="提交" /> <input type="reset" value="重置" /> </div> </form></body></html> |
select--tag.py
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
#!/usr/bin/env python# -*- codinfg:utf-8 -*-'''@author: Jeff LEE@file: select--tag.pay@time: 2020-02-28 10:44'''from selenium import webdriverfrom selenium.webdriver.support.select import Selectfrom time import sleepimport osif 'HTTP_PROXY'in os.environ: del os.environ['HTTP_PROXY']dr = webdriver.Firefox()file_path ='file://'+ os.path.abspath('s7.html')print (file_path)dr.get(file_path)city_selector = Select(dr.find_element_by_tag_name('select'))# 返回所有的optionsprint(city_selector.options)sleep(1)# 返回所有选中的optionsprint(city_selector.all_selected_options)sleep(1)# 通过option的value值来选择上海city_selector.select_by_value('shanghai')sleep(2)# 通过index来选择,比如选择第4项city_selector.select_by_index(3)sleep(1)# 通过option的text来选择city_selector.select_by_visible_text('北京')dr.quit() |