在我们浏览网页的时候经常会碰到下拉框,WebDriver提供了Select类来处理下拉框,详情请往下看:

本章中用到的关键方法如下:

select_by_value():设置下拉框的值 switch_to.alert.accept():定位并接受现有警告框(详情请参考Python爬虫 – Selenium(9)警告框(弹窗)处理) click():鼠标点击事件(其他鼠标事件请参考Python爬虫 – Selenium(5)鼠标事件) move_to_element():鼠标悬停(详情请参考Python爬虫 – Selenium(5)鼠标事件)

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.select import Select
import time
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')

# 鼠标悬停至“设置”链接
link = driver.find_element_by_link_text('设置')
ActionChains(driver).move_to_element(link).perform()
time.sleep(2) #睡两秒,看一下效果

# 打开搜索设置
driver.find_element_by_link_text("搜索设置").click()
time.sleep(2) #睡两秒,看一下效果

# 搜索结果显示条数
sel = driver.find_element_by_xpath("//select[@id='nr']")
Select(sel).select_by_value('50') # 显示50条
time.sleep(2) #睡两秒,看一下效果

# 保存设置
driver.find_element_by_class_name("prefpanelgo").click()
time.sleep(2) #睡两秒,看一下效果

# 定位并接受现有警告框
alert = driver.switch_to.alert.accept()
time.sleep(2) #睡两秒,看一下效果

driver.quit()

select类中的函数列表

 

函数 解析
options 返回select元素所有的options
all_selected_options 返回select元素中所有已选中的选项
first_selected_option 返回select元素中选中的第一个选项
select_by_index(index) 通过索引定位,index索引是从“0”开始
select_by_value(value) 通过value属性值定位
select_by_visible_text(text)t 通过文本值定位,visible_text是在option标签中间的值,即显示在下拉框的值;
deselect_all() 取消全部的已选择项
deselect_by_index(index) 取消已选中的索引项
deselect_by_value(value) 取消已选中的value值
deselect_by_visible_text(text) 取消已选中的文本值

举例

html如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>我是标题</title>
</head>
<body>
<!--select标签-->
<select name="city" size="5" multiple="multiple">
 <option value="1" tabindex="1">北京</option>
 <option value="2" tabindex="2" selected="selected">河南</option>
 <option value="3" tabindex="3">河北</option>
 <option value="4" tabindex="4">山东</option>
 <option value="5" tabindex="5">上海</option>
</select>

</body>
</html>

Python爬虫之Selenium下拉框处理的实现

from selenium import webdriver
from selenium.webdriver.support.select import Select
import time

driver = webdriver.Chrome(r"D:\browser\chromedriver\chromedriver.exe")
driver.get("http://localhost:63342/ui_test/select%E6%A0%87%E7%AD%BE.html")

driver.maximize_window()

ele = driver.find_element_by_name("city")
select = Select(ele)
select.select_by_value("3") # 选中"河北"
time.sleep(3)
select.select_by_index(0) # 选中"北京"
time.sleep(3)
select.deselect_by_value("3") # 取消选中"河北"
time.sleep(3)
select.deselect_by_index(0) # 取消选中"北京"
time.sleep(3)
driver.quit()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。