html5?
一個多選下拉框,沒有默認選
一個單選下拉狂,默認“張桐桐”
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>選擇框</title>
</head>
<body><label for="multiSelect">下拉(多選:</label><select id="multiSelect" multiple><option value="option1">選項1</option><option value="option2">選項2</option><option value="option3">選項3</option></select><br><br><label for="singleSelect">下拉(單選:</label><select id="singleSelect" ><option value="boy" >男</option><option value="girl">女</option><option value="tongtong" selected="selected">張桐桐</option></select>
</body>
</html>
方式1:?傳統點
直接定位到選項,進行click ,? 或者定位到選項,?用send_keys
from selenium import webdriver
import time# 創建瀏覽器驅動對象
from selenium.webdriver.common.by import Bydriver = webdriver.Chrome() # 參數寫瀏覽器驅動文件的路徑,若配置到環境變量就不用寫了
# 訪問網址
driver.get("E:\django\接口準備1\選擇框.html")# (多選框)直接定位到選項元素,然后點擊
"""
兩個點了都會選上
"""
driver.find_element(By.CSS_SELECTOR,'option[value="option1"]').click()
driver.find_element(By.CSS_SELECTOR,'option[value="option3"]').click()# (單選框)
"""
點了一個,之前的會取消掉
"""
time.sleep(2)
driver.find_element(By.CSS_SELECTOR,'option[value="girl"]').click()
time.sleep(2)driver.find_element(By.CSS_SELECTOR,'#singleSelect').send_keys("男")
方式2:實例化一個select?對象來定位
相比上面,?他不是一個點擊行為,而是一個選擇行為,比如默認選了 ,“張桐桐”,?通過方式2的方法再選男,他還是 "張桐桐"
from selenium import webdriver
import time# 創建瀏覽器驅動對象
from selenium.webdriver.common.by import Bydriver = webdriver.Chrome() # 參數寫瀏覽器驅動文件的路徑,若配置到環境變量就不用寫了
# 訪問網址
driver.get("E:\django\接口準備1\選擇框.html")from selenium.webdriver.support.select import Select# 實例化一個選擇對象
selelct1 = Select(driver.find_element(By.CSS_SELECTOR,'#multiSelect'))selelct1.select_by_index(0) # 方式1selelct1.select_by_value("option2") # 方式2
time.sleep(1.5)
selelct1.select_by_visible_text("選項3") # 方式3# 實例化一個選擇對象 (下面的)
select2 = Select(driver.find_element(By.CSS_SELECTOR,'#singleSelect'))select2.select_by_index(0) # 若換成2, 他就還是和默認保持不變selelct1.select_by_index(0)