1. 程式人生 > >selenium Select下拉框

selenium Select下拉框

quit span pow color 我們 body pat int 兩種方法

先來認識一下下拉框,以百度的“高級設置”為例

技術分享圖片

介紹兩種方法來處理下拉框:使用click事件,使用Select方法

  • 使用click事件

上述下拉框的源代碼如下:

技術分享圖片

雖然我們可以在html源文件中看到select的各個選項,但是,如果我們沒有定位到該下拉框的話,是定位不到裏面的子選項的,

所以使用click事件,需要一步一步的點擊

from selenium import webdriver
driver=webdriver.Firefox()
driver.get("https://www.baidu.com/gaoji/advanced.html")

#定位搜索網頁格式下拉框
driver.find_element_by_name("
ft").click() #通過xpath定位子選項 option1=driver.find_element_by_xpath("//*[@name=‘ft‘]/option[1]") option2=driver.find_element_by_xpath("//*[@name=‘ft‘]/option[2]") option3=driver.find_element_by_xpath("//*[@name=‘ft‘]/option[3]") option4=driver.find_element_by_xpath("//*[@name=‘ft‘]/option[4]") #打印選項 print(option1.text)
print(option2.text) print(option3.text) print(option4.text) driver.quit()
  • 使用Select方法
from selenium import webdriver
#導入select模塊
from selenium.webdriver.support.select import Select

driver=webdriver.Firefox()
driver.get("https://www.baidu.com/gaoji/advanced.html")
#d定位下拉框
s=driver.find_element_by_name("
ft") # #通過索引號,值從0開始,每一條option為一個索引 option1=Select(s).select_by_index(0) option2=Select(s).select_by_index(2) # 通過value值,每個option都會有的屬性 option3=Select(s).select_by_value("pdf") option4=Select(s).select_by_value("doc") #通過文本,直接通過選項的文本來定位 option5=Select(s).select_by_visible_text("微軟 Powerpoint (.ppt)") option6=Select(s).select_by_visible_text("RTF 文件 (.rtf)")

Select還提供了其他方法

Select(s).all_selected_options  #返回所有選中的選項
Select(s).options               #f返回所有選項
Select(s).first_selected_option #返回該下拉框第一個選項
Select(s).deselect_by_index()   #取消所有選項

還有很多,不再一一列舉,有興趣可以自行研究

selenium Select下拉框