前言
大家好,我是空空star,本篇給大家分享一下Selenium基礎篇之Select下拉列表選擇。
本篇使用的selenium版本如下:
Version: 4.8.2
本篇使用的瀏覽器如下:
Select介紹
在Selenium中,Select是一個非常有用的類,它用于操作HTML頁面中的下拉列表。使用Select可以方便地選擇下拉列表中的選項,或者獲取下拉列表中已選中的選項。
下面是Select類的常用方法:
select_by_index(index):通過索引選擇下拉列表中的選項。索引從0開始。
select_by_value(value):通過選項的value屬性選擇下拉列表中的選項。
select_by_visible_text(text):通過選項的可見文本選擇下拉列表中的選項。
options:獲取所有選項的列表,每個選項是一個WebElement對象。
all_selected_options:獲取所有已選中的選項,返回一個列表,每個選項是一個WebElement對象。
first_selected_option:獲取第一個已選中的選項,返回一個WebElement對象。
一、頁面準備
先準備一個包含select標簽的html頁面(select_demo.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>空空star</title>
</head>
<body>
<select>
<option value="apple">蘋果</option>
<option value="banana">香蕉</option>
<option value="orange">橘子</option>
<option value="pear">梨</option>
</select>
</body>
</html>


二、場景
Select下拉列表選到橘子??
三、設計
1.引入庫
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from time import sleep
2.啟動瀏覽器實例
driver = webdriver.Chrome()
3.訪問本地演示html文件
driver.get(‘file:///我的路徑/select_demo.html’)
4.定位到select標簽
s = driver.find_element(By.TAG_NAME,‘select’)
5.選擇橘子??
5.1 通過索引
橘子在第三個,索引從0開始
Select(s).select_by_index(2)
5.2 通過value值
橘子的value值是orange
Select(s).select_by_value(‘orange’)
5.3 通過text值
Select(s).select_by_visible_text(‘橘子’)
6.強制等待
為了觀察效果
sleep(5)文章來源:http://www.zghlxwxcb.cn/news/detail-402482.html
7.結(jié)束webdriver進程
driver.quit()文章來源地址http://www.zghlxwxcb.cn/news/detail-402482.html
結(jié)果

到了這里,關于Selenium基礎篇之Select下拉列表選擇的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!