python-web自動化:下拉列表操作


一、認識select
    1.打開百度-設置-搜索設置界面,如下圖所示

    2.箭頭所指位置,就是select選項框,打開頁面元素定位,下方紅色框框區域,可以看到select標簽屬性:
<select id="nr" name="NR">
    3.選項有三個
<option selected="" value="10">每頁顯示10條</option>
<option value="20">每頁顯示20條</option>
<option value="50">每頁顯示50條</option>

 

二:操作

     非select/option元素:

     1.觸發下拉列表出現

     2.等待下拉列表中的元素出現,然后進行選擇元素即可。

 

 

select/option元素:

下拉框操作-Select類
selenium提供Select類來處理select/option

1.引入

from selenium.webdriver.support.ui import Select

2.創建Select對象,傳入元素

ele = driver.find_element_by_xpath(元素定位表達式)
s = Select(ele)

3.選擇下拉列表值:

s.select_by_value(value值) #通過value
s.select_by_index(index) #通過下標
s.select_by_visible_text(文本') #通過文本

 

 
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains as AC 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.ui import Select driver = webdriver.Chrome() driver.get('https://www.baidu.com/') time.sleep(3) # 百度首頁,設置鏈接元素定位 ele = driver.find_element(By.XPATH,"//div[@id='u1']/a[text()='設置']") # 對設置鏈接進行鼠標懸浮操作,實例化類,調用懸浮方法,最后進行操作 AC(driver).move_to_element(ele).perform() # 設置下拉框中選擇【高級搜索】,浮窗下拉列表可用click進行點擊操作 WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//a[text()='高級搜索']"))) driver.find_element_by_xpath("//a[text()='高級搜索']").click() # 等待高級設置搜索頁面可見 WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,'//select[@name="ft"]'))) # 創建Select對象,參數為元素 ele = driver.find_element_by_xpath('//select[@name="ft"]') s = Select(ele) s.select_by_value('xls') #通過value time.sleep(2) s.select_by_index(1) #通過下標 time.sleep(2) s.select_by_visible_text('RTF 文件 (.rtf)') #通過文本
 

 

注意:次案例中的高級搜索案例已改成非select下拉框

改后先定位下拉框中的箭頭觸發下拉列表出現,在操作下拉列表中的元素即可

time.sleep(2)
driver.find_element_by_xpath('//span[@id="adv-setting-ft"]//i[@class="c-icon c-select-arrow"]').click()
driver.find_element_by_xpath('//p[text()="RTF 文件 (.rtf)"]').click()


懸浮下拉列表中的元素如果進行定位,寫表達式

  1. 以百度首頁為例子,在右上角有設置按鈕,鼠標放在設置按鈕上,會懸浮顯示下拉列表
  2. 定位懸浮列表的內容時,需要先讓下拉列表出現,然后再按 shift+ctrl+c 定位下拉列表中的元素;或者出現下拉列表后,右鍵檢查來定位對應的元素


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM