selenium基礎:select下拉框
阿新 • • 發佈:2018-12-16
我們接著講selenium元素操作:滑鼠操作和select下拉框
select下拉框
做自動化過程中,遇到下拉框的情況還是挺多的,一般分為select型別的下拉框和input型別的假下拉框。
對於input型別的下拉框,處理思路是展開下拉列表,等待選擇的元素出現,選擇下拉框中的元素。
這篇部落格我們只重點講select型別的下拉框,藉助Select類
首先匯入Select模組:
1 # coding=utf-8
2 from selenium import webdriver 3 from selenium.webdriver.support.select import Select
1、Select提供了三種選擇選項的方法
1 select_by_index # 通過索引定位
2 select_by_value # 通過value值定位 3 select_by_visible_text # 通過文字值定位
注意事項:
index索引是從“0”開始;
value是option標籤的一個屬性值,並不是顯示在下拉框中的值;
visible_text是在option標籤中間的值,是顯示在下拉框的值;
2、Select提供了三種返回options資訊的方法
1 options # 返回select元素所有的options
2 all_selected_options # 返回select元素中所有已選中的選項 3 first_selected_options # 返回select元素中選中的第一個選項
注意事項:
這三種方法的作用是檢視已選中的元素是否是自己希望選擇的:
options:提供所有選項的元素列表;
all_selected_options:提供所有被選中選項的元素列表;
first_selected_option:提供第一個被選中的選項元素;
3、Select提供了四種取消選中項的方法
1 deselect_all # 取消全部的已選擇項
2 deselect_by_index # 取消已選中的索引項 3 deselect_by_value # 取消已選中的value值 4 deselect_by_visible_text # 取消已選中的文字值
下面以百度頁面為例,點選搜尋設定後,設定搜尋結果顯示為20條
# coding=utf-8 from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time from selenium.webdriver.support.select import Select driver=webdriver.Chrome("D:\Google\Chrome\Application\chromedriver") driver.get('https://www.baidu.com') #點選搜尋設定 time.sleep(5) driver.find_element_by_xpath('//*[@id="u1"]/a[8]').click() time.sleep(1) driver.find_element_by_xpath('//a[text()="搜尋設定"]').click() #等待元素出現 searchset = (By.XPATH, '//li[text()="搜尋設定"]') WebDriverWait(driver, 30, 0.2).until(EC.visibility_of_element_located(searchset)) #例項化Select類 ele=driver.find_element_by_name('NR') s=Select(ele) s.select_by_index(1) #儲存設定 driver.find_element_by_xpath('//a[text()="儲存設定"]').click()