Python高級特性與網絡爬蟲(二):使用Selenium自動化測試工具爬取一號店商品信息

上一篇介紹了Ajax動態渲染的頁面的分析和爬取,通過JavaScript動態渲染的頁面的方式不只有ajax這一種,還有很多其他的方式,分析他們的網頁結構和加密參數難度非常大,爲了解決這樣的頁面的數據爬取,我們可以直接使用模擬瀏覽器運行的方式來實現。python中有很多可以模擬瀏覽器運行的庫,其中最常用的是Selenium,它是一個自動化的web應用的軟件測試工具,利用它可以驅動瀏覽器執行特定的動作,同時也可以獲取瀏覽器當前呈現的頁面的源代碼,這篇博文將向大家簡要介紹一下selenium的使用以及如何通過selenium來爬取一號店的商品信息

Selenium的配置與使用

Selenium庫的安裝與ChromeDriver的配置

我們這裏以selenium驅動Chrome瀏覽器爲例,先在python中通過pip install selenium安裝好selenium庫,之後爲了能夠讓selenium驅動Chrome還需要去下載ChromeDriver,通過國內鏡像網站進行下載http://npm.taobao.org/mirrors/chromedriver/,下載前先要確認自己的Chrome瀏覽器內核版本,如下圖所示,內核版本爲76.0.3809.132,下載的76.0.3809.126親測可用,然後將下載好的chromedriver.exe文件放到python的Script目錄下,配置工作完成。
在這裏插入圖片描述
利用如下一段Python代碼進行測試,如果能成功彈出來一號店首頁,說明配置成功

from selenium import webdriver
browser=webdriver.Chrome() #打開Chrome瀏覽器
browser.get('https://www.yhd.com') #訪問一號店

selenium的使用

接下來我們來結合一號店網頁來具體瞭解一下selenium的使用,通過browser.get(‘https://www.yhd.com’)命令我們獲取了一號店網頁的句柄,然後可以使用browser.page_source命令來獲取網頁源代碼,然後觀察網頁源代碼,這裏爲了便於觀察就向大家展示開發者工具看到的源碼,紅框圈出的部分爲搜索框input和搜索按鈕button,在selenium中我們可以通過find_element_by_id(通過id定位),find_element_by_class(通過class定位)等方法來定位到元素,這裏我們可以通過如下兩條命令定位到搜索框和搜索按鈕:

input_search=browser.find_element_by_class_name('hd_search_ipt')
button=browser.find_element_by_class_name('hd_search_btn')

在這裏插入圖片描述
之後我們可以用send_keys方法向搜索框中輸入搜索內容,然後點擊button進行搜索,命令如下所示:

input_search.send_keys("女僕")
button.click()

之後便會跳轉到商品頁面,如下圖所示,頁面裏每件商品的信息都在右上選中的那個元素的下拉列表裏,可以爬取相應的信息:
在這裏插入圖片描述
爬取完該頁信息之後,需要跳轉到下一頁,由於翻頁的各頁碼元素在網頁加載完成之後還需要再等待一段時間才能加載出來,所以我們需要利用如下代碼來設置等待翻頁元素加載出來之後再獲取該元素,使用selenium中的WebDriverWait和expected_conditions方法,最長等待10s元素加載,獲取第二頁的按鈕點擊即可跳轉到第二頁:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait=WebDriverWait(browser,10)
submit=wait.until(EC.element_to_be_clickable((By.ID,'page_2')))
submit.click()

使用Selenium自動化測試工具爬取一號店商品圖片代碼

介紹完selenium的使用之後,爬取一號店商品信息的代碼已經基本上完成,我們爬取前10頁商品的圖片下載到本地,使用正則表達式獲取商品小圖下載鏈接,python代碼如下所示:

#author:xingfengxueyu
#time:2020/04/25
from selenium import webdriver
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
import requests
import os
browser=webdriver.Chrome()
browser.get('https://www.yhd.com/')
input_1=browser.find_element_by_class_name('hd_search_ipt')
input_1.send_keys("女僕")
button=browser.find_element_by_class_name('hd_search_btn')
button.click()
if not os.path.exists('yhd_np'):
    os.mkdir('yhd_np')  #創建文件夾存放商品圖片
for i in range(2,11):
    soup = BeautifulSoup(browser.page_source, 'lxml')
    for img in soup.find_all(attrs={'class': 'img'}):
        url=re.findall('<img .*?="(.*?)"/>',str(img))[0] 
        if 'src' in url:
            url=re.findall('<img .*?src="(.*?)"/>',str(img))[0]
        url="http:"+url #圖片下載鏈接,有兩種圖片鏈接格式,所以要分別處理
        try:
            pic_r=requests.get(url)
            title=url.split('/')[-1].split('!')[0]
            #print(title)
            with open('yhd_np\{0}'.format(title),'wb') as f:
                f.write(pic_r.content)
        except:
            print(img)
            print(url)
    wait=WebDriverWait(browser,10)
    submit=wait.until(EC.element_to_be_clickable((By.ID,'page_'+str(i))))
    submit.click() #點擊翻頁
browser.close()#關閉瀏覽器

最終各商品的小圖都下載到文件夾中,如下所示:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章