Python Selenium自動(dòng)化實(shí)現(xiàn)網(wǎng)頁操控
1 什么是 Selenium 自動(dòng)化
Selenium 是一個(gè)用于 Web 應(yīng)用程序測(cè)試的工具,支持多種瀏覽器(如 Chrome、Firefox、Edge 等)。WebDriver 是 Selenium 的核心組件,用于控制瀏覽器行為并執(zhí)行自動(dòng)化操作。元素定位是通過各種方式(如 ID、Class Name、XPath 等)在網(wǎng)頁上找到特定元素。
2 為什么要使用 Selenium 自動(dòng)化
Selenium 可以用于自動(dòng)化測(cè)試,減少人工測(cè)試的工作量。Selenium 可以用于抓取動(dòng)態(tài)加載的數(shù)據(jù),這些數(shù)據(jù)通常無法通過簡(jiǎn)單的 HTTP 請(qǐng)求獲取。Selenium 支持多種瀏覽器,確保應(yīng)用在不同瀏覽器上的一致性。
3 什么時(shí)候使用 Selenium 自動(dòng)化
當(dāng)網(wǎng)頁內(nèi)容是通過 JavaScript 動(dòng)態(tài)加載時(shí),Selenium 是抓取這些數(shù)據(jù)的理想工具。當(dāng)需要模擬復(fù)雜的用戶交互(如點(diǎn)擊、輸入、滾動(dòng)等)時(shí),Selenium 非常有用。在需要頻繁進(jìn)行回歸測(cè)試或跨瀏覽器測(cè)試時(shí),Selenium 是首選工具。
4 如何使用 Selenium 自動(dòng)化
安裝 Selenium 庫和瀏覽器驅(qū)動(dòng)(如 ChromeDriver)。打開瀏覽器、導(dǎo)航到 URL、定位元素、點(diǎn)擊、輸入等。處理彈出窗口、等待元素加載、執(zhí)行 JavaScript 等。處理元素未找到、超時(shí)等異常情況。
安裝與配置
安裝 Selenium 庫
pip install selenium==4.5.0
下載瀏覽器驅(qū)動(dòng)(如 ChromeDriver)
將瀏覽器驅(qū)動(dòng)程序的路徑添加到系統(tǒng)環(huán)境變量中。
注意:不同版本的瀏覽器驅(qū)動(dòng)程序支持的瀏覽器版本也不同,在下載瀏覽器驅(qū)動(dòng)程序之前,先查看當(dāng)前瀏覽器的版本號(hào)。
查看 Chrome 瀏覽器版本
單擊 Chrome 瀏覽器右上角的圖標(biāo)打開 “自定義及控制 Google Chrome” 菜單,在該菜單中選擇 “幫助”→“關(guān)于 Google Chrome” 打開關(guān)于 Chrome 頁面。

訪問 chromedriver 官網(wǎng)
根據(jù) Chrome 瀏覽器的版本號(hào),到 chromedriver官網(wǎng) 官方網(wǎng)站或者到 最新最全的外網(wǎng)
chromedriver驅(qū)動(dòng)網(wǎng)站與Chrome瀏覽器版本對(duì)應(yīng)的chromedriver的下載列表,下載對(duì)應(yīng)版本的 ChromeDriver。

下載 chromedriver
單擊與瀏覽器相應(yīng)版本的 ChromeDriver 鏈接,進(jìn)入下載頁面,下載 ZIP 格式的壓縮包到本地,解壓后得到 chromedriver.exe。

WebDriver 的配置
將 WebDriver 配置到系統(tǒng)環(huán)境變量后,程序中再次使用 WebDriver 時(shí),就不需要重復(fù)指定 WebDriver 的執(zhí)行路徑了。
5 selenium 的基本使用
from selenium import webdriver
?
url = 'https://www.baidu.com'
?
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
?
# 打開網(wǎng)頁
browser.get(url)
# 獲取源碼(同requests.text)
print(browser.page_source)
input('用戶按下回車鍵退出')
# 退出
browser.quit()6 Selenium 元素定位
元素定位首先要找到它們,WebDriver 提供很多定位元素的方法:
| 定位方式 | By 標(biāo)識(shí)符 | 示例 |
|---|---|---|
| ID | By.ID | find_element(By.ID, "kw") |
| Name 屬性 | By.NAME | find_element(By.NAME, "wd") |
| Class name | By.CLASS_NAME | find_element(By.CLASS_NAME, "s_ipt") |
| 標(biāo)簽名 | By.TAG_NAME | find_elements(By.TAG_NAME, "input") |
| 鏈接文本 | By.LINK_TEXT | find_element(By.LINK_TEXT, "新聞") |
| 部分鏈接文本 | By.PARTIAL_LINK_TEXT | find_element(By.PARTIAL_LINK_TEXT, "新") |
| CSS 選擇器 | By.CSS_SELECTOR | find_element(By.CSS_SELECTOR, "#su") |
| XPath | By.XPATH | find_element(By.XPATH, '//input[@id="su"]') |
代碼演示:selenium 的元素定位
from selenium import webdriver
# 定位元素,必須要導(dǎo)入By
from selenium.webdriver.common.by import By
?
url = 'https://www.baidu.com'
?
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
?
# 打開網(wǎng)頁
browser.get(url)
?
# 通過id獲取輸入框
res1 = browser.find_element(By.ID,'kw')
print(res1)
?
# 通過name獲取輸入框
res2 = browser.find_element(By.NAME,'wd')
print(res2)
?
# 通過XPath獲取輸入框
res3 = browser.find_element(By.XPATH,"http://*/input[@id='kw']")
print(res3)
print(res1==res2 and res2==res3)# True
?
# 通過類名獲取輸入框
res4 = browser.find_element(By.CLASS_NAME,"s_ipt")
?
# 通過css選擇器來獲取輸入框
res5 = browser.find_element(By.CSS_SELECTOR,"#kw")
print(res3==res4 and res4==res5)# True
?
# 通過通過鏈接文本獲取標(biāo)簽
res6 = browser.find_element(By.LINK_TEXT,"新聞")
?
# 通過部分鏈接文本獲取標(biāo)簽
res7 = browser.find_element(By.PARTIAL_LINK_TEXT,"聞")
print(res6==res7)# True
?
# 通過標(biāo)簽名,并且由復(fù)數(shù)的形式獲取a標(biāo)簽
res8 = browser.find_elements(By.TAG_NAME,"a")
print(res8)
?
input('用戶按下回車鍵退出~')
# 退出
browser.quit()7 訪問元素信息
獲取元素屬性 .get_attribute('class'),獲取元素文本 .text,獲取標(biāo)簽名.tag_name。
8 元素信息獲取
from selenium import webdriver
from selenium.webdriver.common.by import By
?
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
?
url = "https://www.baidu.com"
# 打開網(wǎng)頁
browser.get(url)
?
# 獲取到新聞文本的a鏈接(通過鏈接文本內(nèi)容)
a = browser.find_element(By.LINK_TEXT,"新聞")
?
# 獲取href
a_href = a.get_attribute('href')
print(f"href:{a_href}")
# 結(jié)果:href:http://news.baidu.com/
?
# 獲取class
a_class = a.get_attribute('class')
print(f"class:{a_class}")
# 結(jié)果:class:mnav c-font-normal c-color-t
?
# 獲取文本內(nèi)容
a_text = a.text
print(a_text)
# 結(jié)果:新聞
?
# 獲取標(biāo)簽名稱
a_tag_name = a.tag_name
print(a_tag_name)
# 結(jié)果:a9 交互操作
點(diǎn)擊、send_keys()、后退操作、前進(jìn)操作、模擬 JS 滾動(dòng)、執(zhí)行 JS 代碼、獲取網(wǎng)頁代碼 page_source、退出。
selenium 元素交互
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
?
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
# 將窗口最大化
# browser.maximize_window()
?
url = 'https://www.baidu.com'
# 打開瀏覽器
browser.get(url)
?
# 獲取輸入框
get_input = browser.find_element(By.ID,"kw")
# 輸入周杰倫
get_input.send_keys('周杰倫')
?
# 獲取點(diǎn)擊按鈕
get_button = browser.find_element(By.CSS_SELECTOR,"input[type='submit']")
# 執(zhí)行點(diǎn)擊操作
get_button.click()
?
def scoll():
# 這里要進(jìn)行等待,否則后面的滑動(dòng)頁面沒有反應(yīng),目的是等待頁面加載
time.sleep(2)
# 執(zhí)行滑動(dòng)
js = 'document.documentElement.scrollTop=100000'
browser.execute_script(js)
def next_page():
scoll()
time.sleep(2)
# 獲取下一頁按鈕
next_button = browser.find_element(By.PARTIAL_LINK_TEXT,"下一頁")
# 執(zhí)行點(diǎn)擊操作
next_button.click()
for i in range(3):
next_page()
# 導(dǎo)航操作
browser.back() # 回退
time.sleep(2)
browser.forward() # 前進(jìn)
input('回車鍵退出程序~')
browser.quit()10 案例練習(xí)
12306 注冊(cè)下拉框功能實(shí)現(xiàn)
# 導(dǎo)入模塊
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select # 專門處理下拉框
?
# 目標(biāo)網(wǎng)站
url = 'https://kyfw.12306.cn/otn/regist/init'
?
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
?
# 打開網(wǎng)頁
browser.get(url)
?
# 獲取下拉框?qū)ο?
get_selector = browser.find_element(By.ID,'cardType')
# 實(shí)例化Selectors對(duì)象
selector = Select(get_selector)
time.sleep(2)
# 使用value來選定
# selector.select_by_value('B')
# 使用索引來選擇
selector.select_by_index(5)
input('回車鍵退出程序~')
browser.quit()11 案例實(shí)戰(zhàn)
目標(biāo)
開發(fā)一個(gè)爬蟲程序,從蘇寧易購網(wǎng)站抓取口紅商品信息,并保存為 CSV 文件。
目標(biāo)網(wǎng)址
蘇寧易購(Suning.com)
要求
- 商品信息采集:實(shí)現(xiàn)蘇寧易購平臺(tái)特定商品(口紅)信息的自動(dòng)化采集,支持多頁數(shù)據(jù)連續(xù)采集。
- 用戶交互模擬:實(shí)現(xiàn)瀏覽器自動(dòng)化操作,模擬真實(shí)用戶搜索行為,處理頁面動(dòng)態(tài)加載內(nèi)容。
- 數(shù)據(jù)存儲(chǔ)與分析:結(jié)構(gòu)化存儲(chǔ)商品信息,支持后續(xù)數(shù)據(jù)分析處理,提供可擴(kuò)展的數(shù)據(jù)存儲(chǔ)方案。
需求
商品信息包括:商品名、評(píng)論數(shù)、價(jià)格、店鋪名、詳情頁鏈接。
頁面結(jié)構(gòu)分析
通過分析,每個(gè)商品都是一個(gè) <li> 標(biāo)簽,這一頁的所有數(shù)據(jù)都在一個(gè) <ul> 標(biāo)簽里面。
實(shí)現(xiàn)思路分析
- 打開網(wǎng)站
- 輸入內(nèi)容(口紅)
- 點(diǎn)擊搜索
- 拖動(dòng)滾輪到底部
- 爬取數(shù)據(jù) / 解析數(shù)據(jù)
- 翻頁處理
實(shí)現(xiàn)代碼:
# 導(dǎo)入模塊
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import csv
# 目標(biāo)網(wǎng)站
url = 'https://www.suning.com/'
# 創(chuàng)建瀏覽器操作對(duì)象
browser = webdriver.Chrome()
browser.maximize_window()
# 打開網(wǎng)頁
browser.get(url)
# 獲取輸入框?qū)ο?
input_element = browser.find_element(By.ID,"searchKeywords")
# 執(zhí)行輸入
input_element.send_keys('口紅')
time.sleep(1)
# 獲取點(diǎn)擊按鈕
button_element = browser.find_element(By.ID,"searchSubmit")
# 執(zhí)行點(diǎn)擊
button_element.click()
time.sleep(1)
# 下滑
def drop_down():
time.sleep(6)
for x in range(1,12,2):
time.sleep(1)
j = x / 9
js = f'document.documentElement.scrollTop = document.documentElement.scrollHeight * {j}'
browser.execute_script(js)
# 獲取數(shù)據(jù)
def get_info():
# 先執(zhí)行下拉
drop_down()
# 構(gòu)建字典
info_dict = {
'商品名稱':"",
'商品價(jià)格':"",
'評(píng)論數(shù)':"",
'店鋪名稱':"",
'詳情鏈接':"",
'圖片url':""
}
# 獲取每一個(gè)盒子
list_box = browser.find_elements(By.CLASS_NAME,"product-box ")
if list_box:
for box in list_box:
# 獲取商品名稱
title = box.find_element(By.CSS_SELECTOR,".title-selling-point > a").text
info_dict['商品名稱'] = title
# 獲取商品價(jià)格
price = box.find_element(By.CSS_SELECTOR,".def-price").text
info_dict['商品價(jià)格'] = price
# 獲取評(píng)論數(shù)
comment = box.find_element(By.CSS_SELECTOR,".info-evaluate > a").text
info_dict['評(píng)論數(shù)'] = comment
# 獲取店鋪名稱
dianpu = box.find_element(By.CSS_SELECTOR,".store-stock > a").text
info_dict['店鋪名稱'] = dianpu
# 獲取詳情鏈接
detail_url = box.find_element(By.CSS_SELECTOR,".title-selling-point > a").get_attribute('href')
info_dict['詳情鏈接'] = detail_url
# 獲取圖片url
photo_url = box.find_element(By.CSS_SELECTOR,".sellPoint > img").get_attribute('src')
info_dict['圖片url'] = photo_url
csv_writer.writerow(info_dict)
print(info_dict)
else:
print('沒有獲取到所有盒子')
flag = True
i = 1
with open('蘇寧易購_口紅.csv','w',newline='',encoding='utf-8') as f:
field_list = ['商品名稱','商品價(jià)格','評(píng)論數(shù)','店鋪名稱','詳情鏈接','圖片url']
csv_writer = csv.DictWriter(f,fieldnames=field_list)
csv_writer.writeheader()
while flag:
try:
print(f'正在獲取第{i}頁內(nèi)容')
# 調(diào)用獲取內(nèi)容函數(shù)
get_info()
# # 獲取下一頁按鈕
# next_page_btn = browser.find_element(By.ID,"nextPage")
# # 執(zhí)行點(diǎn)擊下一頁
# next_page_btn.click()
# 翻頁
browser.execute_script('document.querySelector("#nextPage").click()')
time.sleep(2) # 等待頁面加載
i += 1
except Exception as e:
flag = False
print('已經(jīng)是最后一頁了')
input('回車鍵結(jié)束')
browser.quit()以上就是Python Selenium自動(dòng)化實(shí)現(xiàn)網(wǎng)頁操控的詳細(xì)內(nèi)容,更多關(guān)于Python Selenium網(wǎng)頁操作的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python學(xué)習(xí)小技巧之列表項(xiàng)的排序
這篇文章主要給大家介紹了Python學(xué)習(xí)小技巧之列表項(xiàng)排序的相關(guān)資料,文中介紹的非常詳細(xì),需要的朋友們可以參借鑒,下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。2017-05-05
python中print的不換行即時(shí)輸出的快速解決方法
下面小編就為大家?guī)硪黄猵ython中print的不換行即時(shí)輸出的快速解決方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考2016-07-07
Python?虛擬環(huán)境的價(jià)值和常用命令詳解
在實(shí)際項(xiàng)目開發(fā)中,我們通常會(huì)根據(jù)自己的需求去下載各種相應(yīng)的框架庫,如Scrapy、Beautiful?Soup等,但是可能每個(gè)項(xiàng)目使用的框架庫并不一樣,或使用框架的版本不一樣,今天給大家分享下Python?虛擬環(huán)境的價(jià)值和常用命令,感興趣的朋友一起看看吧2022-05-05
Python實(shí)現(xiàn)合并兩個(gè)列表的方法分析
這篇文章主要介紹了Python實(shí)現(xiàn)合并兩個(gè)列表的方法,結(jié)合實(shí)例形式對(duì)比分析了常見的Python列表合并操作技巧,需要的朋友可以參考下2018-05-05
python實(shí)現(xiàn)自動(dòng)登錄12306自動(dòng)搶票功能
隨著互聯(lián)網(wǎng)技術(shù)的發(fā)展,越來越多的人選擇通過網(wǎng)絡(luò)平臺(tái)購票,特別是在中國,12306作為官方火車票預(yù)訂平臺(tái),承擔(dān)了巨大的訪問量,對(duì)于熱門線路或者節(jié)假日出行,往往會(huì)出現(xiàn)一票難求的情況,因此,一些技術(shù)愛好者嘗試?yán)镁幊陶Z言如Python來開發(fā)搶票腳本2025-01-01

