Python爬蟲之Selenium下拉框處理的實現
阿新 • • 發佈:2020-12-05
在我們瀏覽網頁的時候經常會碰到下拉框,WebDriver提供了Select類來處理下拉框,詳情請往下看:
本章中用到的關鍵方法如下:
- select_by_value():設定下拉框的值
- switch_to.alert.accept():定位並接受現有警告框(詳情請參考Python爬蟲 - Selenium(9)警告框(彈窗)處理)
- click():滑鼠點選事件(其他滑鼠事件請參考Python爬蟲 - Selenium(5)滑鼠事件)
- move_to_element():滑鼠懸停(詳情請參考Python爬蟲 - Selenium(5)滑鼠事件)
from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.support.select import Select import time driver = webdriver.Chrome() driver.get('http://www.baidu.com') # 滑鼠懸停至“設定”連結 link = driver.find_element_by_link_text('設定') ActionChains(driver).move_to_element(link).perform() time.sleep(2) #睡兩秒,看一下效果 # 開啟搜尋設定 driver.find_element_by_link_text("搜尋設定").click() time.sleep(2) #睡兩秒,看一下效果 # 搜尋結果顯示條數 sel = driver.find_element_by_xpath("//select[@id='nr']") Select(sel).select_by_value('50') # 顯示50條 time.sleep(2) #睡兩秒,看一下效果 # 儲存設定 driver.find_element_by_class_name("prefpanelgo").click() time.sleep(2) #睡兩秒,看一下效果 # 定位並接受現有警告框 alert = driver.switch_to.alert.accept() time.sleep(2) #睡兩秒,看一下效果 driver.quit()
select類中的函式列表
函式 | 解析 |
---|---|
options | 返回select元素所有的options |
all_selected_options | 返回select元素中所有已選中的選項 |
first_selected_option | 返回select元素中選中的第一個選項 |
select_by_index(index) | 通過索引定位,index索引是從“0”開始 |
select_by_value(value) | 通過value屬性值定位 |
select_by_visible_text(text)t | 通過文字值定位,visible_text是在option標籤中間的值,即顯示在下拉框的值; |
deselect_all() | 取消全部的已選擇項 |
deselect_by_index(index) | 取消已選中的索引項 |
deselect_by_value(value) | 取消已選中的value值 |
deselect_by_visible_text(text) | 取消已選中的文字值 |
舉例
html如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我是標題</title> </head> <body> <!--select標籤--> <select name="city" size="5" multiple="multiple"> <option value="1" tabindex="1">北京</option> <option value="2" tabindex="2" selected="selected">河南</option> <option value="3" tabindex="3">河北</option> <option value="4" tabindex="4">山東</option> <option value="5" tabindex="5">上海</option> </select> </body> </html>
from selenium import webdriver from selenium.webdriver.support.select import Select import time driver = webdriver.Chrome(r"D:\browser\chromedriver\chromedriver.exe") driver.get("http://localhost:63342/ui_test/select%E6%A0%87%E7%AD%BE.html") driver.maximize_window() ele = driver.find_element_by_name("city") select = Select(ele) select.select_by_value("3") # 選中"河北" time.sleep(3) select.select_by_index(0) # 選中"北京" time.sleep(3) select.deselect_by_value("3") # 取消選中"河北" time.sleep(3) select.deselect_by_index(0) # 取消選中"北京" time.sleep(3) driver.quit()
到此這篇關於Python爬蟲之Selenium下拉框處理的實現的文章就介紹到這了,更多相關Selenium 下拉框內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!