溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

發(fā)布時間:2021-12-08 11:14:14 來源:億速云 閱讀:137 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取”,在日常操作中,相信很多人在Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

一、Selenium介紹與配置

1.Selenium簡介

Selenium 是ThoughtWorks專門為Web應用程序編寫的一個驗收測試工具。Selenium測試直接運行在瀏覽器中,可以模擬真實用戶的行為。支持的瀏覽器包括IE(7、8、9)、Mozilla Firefox、Mozilla Suite等。這個工具的主要功能包括:測試與瀏覽器的兼容性——測試你的應用程序看是否能夠很好地工作在不同瀏覽器和操作系統(tǒng)之上。測試系統(tǒng)功能——創(chuàng)建回歸測試檢驗軟件功能和用戶需求。

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ā)者工具中找到輸入框

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

輸入要查詢的值并通過button點擊事件實現(xiàn)

input_btn = web.find_element_by_id('kw')
input_btn.send_keys('原神', Keys.ENTER)

測試:

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

三、爬取動態(tài)網(wǎng)頁的名人名言

1. 網(wǎng)頁數(shù)據(jù)分析

在開發(fā)者工具中查看每一組名言(名言+名人)的位置:

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

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

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

且名句在class="text"的<span>標簽中,作者在class="author"的small標簽中。

2. 翻頁分析

在開發(fā)者工具中查看Next翻頁按鈕

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

可發(fā)現(xiàn)Next按鈕只有href屬性,無法定位。但可以通過查找網(wǎng)頁最后一個有aria-hidden屬性的span標簽,進行點擊以跳轉(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ù)

代碼準備:

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()

爬取結果:

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

四、爬取京東網(wǎng)站書籍信息

爬取某個關鍵字書籍的前三頁書籍信息,本文以計算機圖形學為例

1.進入網(wǎng)頁并搜索計算機圖形學

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('計算機圖形學', Keys.ENTER)  # 找到輸入框輸入,回車

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

成功。

2.網(wǎng)頁分析

使用開發(fā)者工具可查看每一個商品信息的位置

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

發(fā)現(xiàn)每一個商品信息都存在于class包含gl-item的li中。因此獲取該頁面下所有l(wèi)i,由此爬取書籍信息(包括書名和價格)。

3.翻頁

web.find_element_by_class_name('pn-next').click()  # 點擊下一頁

4.數(shù)據(jù)保存

with open('計算機圖形學.csv', 'w', encoding='utf-8')as fp:
    writer = csv.writer(fp)
    writer.writerow(['書名', '價格', '作者', '出版社', '預覽圖片地址'])
    writer.writerows(all_book_info)

5.代碼準備

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('計算機圖形學', Keys.ENTER)  


def get_onePage_info(web):
    web.execute_script('window.scrollTo(0, document.body.scrollHeight);')
    time.sleep(2)
    page_text = web.page_source

    # 進行解析
    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]   # 價格
        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('計算機圖形學', 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()  # 點擊下一頁
        time.sleep(2)
    with open('計算機圖形學.csv', 'w', encoding='utf-8')as fp:
        writer = csv.writer(fp)
        writer.writerow(['書名', '價格', '作者', '出版社', '預覽圖片地址'])
        writer.writerows(all_book_info)

if __name__ == '__main__':
    main()

爬取結果

Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取

成功

到此,關于“Python基于Selenium怎么實現(xiàn)動態(tài)網(wǎng)頁信息的爬取”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI