Python?基于Selenium實(shí)現(xiàn)動態(tài)網(wǎng)頁信息的爬取
一、Selenium介紹與配置
1.Selenium簡介
Selenium 是ThoughtWorks專門為Web應(yīng)用程序編寫的一個(gè)驗(yàn)收測試工具。Selenium測試直接運(yùn)行在瀏覽器中,可以模擬真實(shí)用戶的行為。支持的瀏覽器包括IE(7、8、9)、Mozilla Firefox、Mozilla Suite等。這個(gè)工具的主要功能包括:測試與瀏覽器的兼容性——測試你的應(yīng)用程序看是否能夠很好地工作在不同瀏覽器和操作系統(tǒng)之上。測試系統(tǒng)功能——創(chuàng)建回歸測試檢驗(yàn)軟件功能和用戶需求。
2. Selenium+Python環(huán)境配置
pip install selenium
二、網(wǎng)頁自動化測試
1.啟動瀏覽器并打開百度搜索
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
2.定位元素
在開發(fā)者工具中找到輸入框

輸入要查詢的值并通過button點(diǎn)擊事件實(shí)現(xiàn)
input_btn = web.find_element_by_id('kw')
input_btn.send_keys('原神', Keys.ENTER)
測試:

三、爬取動態(tài)網(wǎng)頁的名人名言
1. 網(wǎng)頁數(shù)據(jù)分析
在開發(fā)者工具中查看每一組名言(名言+名人)的位置:

現(xiàn)每一組名言都是在class="quote"的div中,并且沒有其他class="quote的標(biāo)簽。

且名句在class="text"的<span>標(biāo)簽中,作者在class="author"的small標(biāo)簽中。
2. 翻頁分析
在開發(fā)者工具中查看Next翻頁按鈕

可發(fā)現(xiàn)Next按鈕只有href屬性,無法定位。但可以通過查找網(wǎng)頁最后一個(gè)有aria-hidden屬性的span標(biāo)簽,進(jìn)行點(diǎn)擊以跳轉(zhuǎn)到下一頁。
3.爬取數(shù)據(jù)的存儲
爬取后的數(shù)據(jù)需要存儲至csv文件中,編寫代碼如下:
with open('Saying.csv', 'w', encoding='utf-8')as fp:
fileWrite = csv.writer(fp)
fileWrite.writerow(['名言', '名人'])
fileWrite.writerows(sayingAndAuthor)
web.close()
4. 爬取數(shù)據(jù)
代碼準(zhǔn)備:
from selenium.webdriver import Chrome
import time
import csv
web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
web.get('http://quotes.toscrape.com/js/')
sayingAndAuthor = []
n = 5
for i in range(0, n):
div_list = web.find_elements_by_class_name('quote')
for div in div_list:
saying = div.find_element_by_class_name('text').text
author = div.find_element_by_class_name('author').text
info = [saying, author]
sayingAndAuthor.append(info)
print('成功爬取第' + str(i + 1) + '頁')
if i == n-1:
break
web.find_elements_by_css_selector('[aria-hidden]')[-1].click()
time.sleep(2)
with open('Saying.csv', 'w', encoding='utf-8')as fp:
fileWrite = csv.writer(fp)
fileWrite.writerow(['名言', '名人']) # 寫入表頭
fileWrite.writerows(sayingAndAuthor)
web.close()
爬取結(jié)果:

四、爬取京東網(wǎng)站書籍信息
爬取某個(gè)關(guān)鍵字書籍的前三頁書籍信息,本文以計(jì)算機(jī)圖形學(xué)為例
1.進(jìn)入網(wǎng)頁并搜索計(jì)算機(jī)圖形學(xué)
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
web.get('https://www.jd.com/')
web.maximize_window()
web.find_element_by_id('key').send_keys('計(jì)算機(jī)圖形學(xué)', Keys.ENTER) # 找到輸入框輸入,回車

成功。
2.網(wǎng)頁分析
使用開發(fā)者工具可查看每一個(gè)商品信息的位置

發(fā)現(xiàn)每一個(gè)商品信息都存在于class包含gl-item的li中。因此獲取該頁面下所有l(wèi)i,由此爬取書籍信息(包括書名和價(jià)格)。
3.翻頁
web.find_element_by_class_name('pn-next').click() # 點(diǎn)擊下一頁
4.數(shù)據(jù)保存
with open('計(jì)算機(jī)圖形學(xué).csv', 'w', encoding='utf-8')as fp:
writer = csv.writer(fp)
writer.writerow(['書名', '價(jià)格', '作者', '出版社', '預(yù)覽圖片地址'])
writer.writerows(all_book_info)
5.代碼準(zhǔn)備
from selenium.webdriver import Chrome
from selenium.webdriver.common.keys import Keys
import time
from lxml import etree
import csv
web = Chrome(r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
web.get('https://www.jd.com/')
web.maximize_window()
web.find_element_by_id('key').send_keys('計(jì)算機(jī)圖形學(xué)', Keys.ENTER)
def get_onePage_info(web):
web.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(2)
page_text = web.page_source
# 進(jìn)行解析
tree = etree.HTML(page_text)
li_list = tree.xpath('//li[contains(@class,"gl-item")]')
book_infos = []
for li in li_list:
book_name = ''.join(
li.xpath('.//div[@class="p-name"]/a/em/text()')) # 書名
price = '¥' + \
li.xpath('.//div[@class="p-price"]/strong/i/text()')[0] # 價(jià)格
author_span = li.xpath('.//span[@class="p-bi-name"]/a/text()')
if len(author_span) > 0: # 作者
author = author_span[0]
else:
author = '無'
store_span = li.xpath(
'.//span[@class="p-bi-store"]/a[1]/text()') # 出版社
if len(store_span) > 0:
store = store_span[0]
else:
store = '無'
img_url_a = li.xpath('.//div[@class="p-img"]/a/img')[0]
if len(img_url_a.xpath('./@src')) > 0:
img_url = 'https' + img_url_a.xpath('./@src')[0] # 書本圖片地址
else:
img_url = 'https' + img_url_a.xpath('./@data-lazy-img')[0]
one_book_info = [book_name, price, author, store, img_url]
book_infos.append(one_book_info)
return book_infos
def main():
web = Chrome(
r"D:\\DevTools\\Anaconda\\download\\Anaconda3\\Lib\\site-packages\\selenium\\webdriver\\chrome\\chromedriver.exe")
web.get('https://www.jd.com/')
web.maximize_window()
web.find_element_by_id('key').send_keys('計(jì)算機(jī)圖形學(xué)', Keys.ENTER) # 找到輸入框輸入,回車
time.sleep(2)
all_book_info = []
for i in range(0, 3):
all_book_info += get_onePage_info(web)
print('爬取第' + str(i+1) + '頁成功')
web.find_element_by_class_name('pn-next').click() # 點(diǎn)擊下一頁
time.sleep(2)
with open('計(jì)算機(jī)圖形學(xué).csv', 'w', encoding='utf-8')as fp:
writer = csv.writer(fp)
writer.writerow(['書名', '價(jià)格', '作者', '出版社', '預(yù)覽圖片地址'])
writer.writerows(all_book_info)
if __name__ == '__main__':
main()
爬取結(jié)果

成功
五、總結(jié)
本文通過Selenium和webdrive等庫,對動態(tài)網(wǎng)頁的信息進(jìn)行爬取。?
以上就是Python 基于Selenium實(shí)現(xiàn)動態(tài)網(wǎng)頁信息的爬取的詳細(xì)內(nèi)容,更多關(guān)于Python Selenium 網(wǎng)頁信息爬取的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python編程matplotlib繪圖挑鉆石seaborn小提琴和箱線圖
這篇文章主要為大家介紹了Python編程如何使用matplotlib繪圖來挑出完美的鉆石以及seaborn小提琴和箱線圖,有需要的朋友可以借鑒參考下,希望能夠優(yōu)速幫助2021-10-10
使用matplotlib實(shí)現(xiàn)在同一個(gè)窗口繪制多個(gè)圖形
這篇文章主要介紹了使用matplotlib實(shí)現(xiàn)在同一個(gè)窗口繪制多個(gè)圖形問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
關(guān)于Pycharm無法debug問題的總結(jié)
今天小編就為大家分享一篇關(guān)于Pycharm無法debug問題的總結(jié),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
python使用aiohttp通過設(shè)置代理爬取基金數(shù)據(jù)簡單示例
這篇文章主要為大家介紹了python使用aiohttp通過設(shè)置代理爬取基金數(shù)據(jù)簡單示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
python-opencv 將連續(xù)圖片寫成視頻格式的方法
今天小編就為大家分享一篇python-opencv 將連續(xù)圖片寫成視頻格式的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01

