1. 程式人生 > >Python爬蟲入門教程【7】: 蜂鳥網圖片爬取之二

Python爬蟲入門教程【7】: 蜂鳥網圖片爬取之二

蜂鳥網圖片--簡介

今天玩點新鮮的,使用一個新庫 aiohttp ,利用它提高咱爬蟲的爬取速度。

安裝模組常規套路

pip install aiohttp

執行之後等待,安裝完畢,想要深造,那麼官方文件必備 :https://aiohttp.readthedocs.io/en/stable/

接下來就可以開始寫程式碼了。

我們要爬取的頁面,這一次選取的是

http://bbs.fengniao.com/forum/forum_101_1_lastpost.html

開啟頁面,我們很容易就獲取到了頁碼

好久沒有這麼方便的看到頁碼了。

嘗試用 aiohttp 訪問這個頁面吧,模組的引入,沒有什麼特殊的,採用 import

即可 如果我們需要 使用Asyncio + Aiohttp非同步IO 編寫爬蟲,那麼需要注意,你需要非同步的方法前面加上async

接下來,先嚐試去獲取一下上面那個地址的網頁原始碼。

程式碼中,先宣告一個fetch_img_url的函式,同時攜帶一個引數,這個引數也可以直接寫死。

with 上下文不在提示,自行搜尋相關資料即可 (`・ω・´)

aiohttp.ClientSession() as session: 建立一個session物件,然後用該session物件去開啟網頁。session可以進行多項操作,比如post, get, put

程式碼中 await response.text()

等待網頁資料返回

asyncio.get_event_loop建立執行緒,run_until_complete方法負責安排執行 tasks中的任務。tasks可以為單獨的函式,也可以是列表。

import aiohttp  
import asyncio 

async def fetch_img_url(num):
    url = f'http://bbs.fengniao.com/forum/forum_101_{num}_lastpost.html'  # 字串拼接
    # 或者直接寫成 url = 'http://bbs.fengniao.com/forum/forum_101_1_lastpost.html'
    print(url)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400',
    }

    async with aiohttp.ClientSession() as session:
        # 獲取輪播圖地址
        async with session.get(url,headers=headers) as response:
            try:
                html = await response.text()   # 獲取到網頁原始碼
                print(html)

            except Exception as e:
                print("基本錯誤")
                print(e)

# 這部分你可以直接臨摹
loop = asyncio.get_event_loop()
tasks = asyncio.ensure_future(fetch_img_url(1))
results = loop.run_until_complete(tasks)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視訊,這裡是Python學習者的聚集地,零基礎,進階,都歡迎

上面程式碼最後一部分也可以寫成

loop = asyncio.get_event_loop()
tasks =  [fetch_img_url(1)]
results = loop.run_until_complete(asyncio.wait(tasks))

好了,如果你已經成果的獲取到了原始碼,那麼距離最終的目的就差那麼一丟丟了。 修改程式碼為批量獲取10頁。 只需要修改tasks即可,在此執行,看到如下結果

tasks =  [fetch_img_url(num) for num in range(1, 10)]

下面的一系列操作和上一篇部落格非常類似,找規律。 隨便開啟一個頁面

http://bbs.fengniao.com/forum/forum_101_4_lastpost.html

點選一張圖片,進入內頁,在點選內頁的一張圖片,進入到一個輪播頁面

再次點選進入圖片播放頁面

最後我們在圖片播放頁面,找到原始碼中發現了所有的圖片連結,那麼問題出來了,如何從上面的第一個連結,轉變成輪播圖的連結??? 下面的原始碼是在 http://bbs.fengniao.com/forum/pic/slide_101_10408464_89383854.html 右鍵檢視原始碼。

繼續分析吧~~~~ ヾ(=・ω・=)o

http://bbs.fengniao.com/forum/forum_101_4_lastpost.html
轉變成下面的連結?
http://bbs.fengniao.com/forum/pic/slide_101_10408464_89383854.html

繼續看第一個連結,我們使用F12開發者工具,去抓取一個圖片看看。

圖片中標黃色框的位置,發現了我們想要的數字,那麼好了,我們只需要通過正則表示式把他們匹配出來就好了。 程式碼在下面####的位置,需要注意的是,我採用的原始的正則匹配,在編寫正則表示式的過程中,我發現一步竟然沒有完整匹配,只能分成兩個步驟了,你可以看一下具體的細節o(╥﹏╥)o

  1. 查詢所有的圖片<div class="picList">
  2. 獲取我們想要的兩部分數字
async def fetch_img_url(num):
    url = f'http://bbs.fengniao.com/forum/forum_101_{num}_lastpost.html'
    print(url)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6726.400 QQBrowser/10.2.2265.400',
    }

    async with aiohttp.ClientSession() as session:
        # 獲取輪播圖地址
        async with session.get(url,headers=headers) as response:
            try:
                ###############################################
                url_format = "http://bbs.fengniao.com/forum/pic/slide_101_{0}_{1}.html"
                html = await response.text()   # 獲取到網頁原始碼
                pattern = re.compile('<div class="picList">([\s\S.]*?)</div>')
                first_match = pattern.findall(html)
                href_pattern = re.compile('href="/forum/(\d+?)_p(\d+?)\.html')
                urls = [url_format.format(href_pattern.search(url).group(1), href_pattern.search(url).group(2)) for url in first_match]
                ##############################################

            except Exception as e:
                print("基本錯誤")
                print(e)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視訊,這裡是Python學習者的聚集地,零基礎,進階,都歡迎

程式碼完成,我們已經獲取到,我們想要的URL了,下面繼續讀取URL內部資訊,然後匹配我們想要的圖片連結

async def fetch_img_url(num):
    # 去抄上面的程式碼
    async with aiohttp.ClientSession() as session:
        # 獲取輪播圖地址
        async with session.get(url,headers=headers) as response:
            try:
                #去抄上面的程式碼去吧
                ################################################################
                for img_slider in urls:
                    try:
                        async with session.get(img_slider, headers=headers) as slider:
                            slider_html = await slider.text()   # 獲取到網頁原始碼
                            try:
                                pic_list_pattern = re.compile('var picList = \[(.*)?\];')
                                pic_list = "[{}]".format(pic_list_pattern.search(slider_html).group(1))
                                pic_json = json.loads(pic_list)  # 圖片列表已經拿到
                                print(pic_json)
                            except Exception as e:
                                print("程式碼除錯錯誤")
                                print(pic_list)
                                print("*"*100)
                                print(e)

                    except Exception as e:
                        print("獲取圖片列表錯誤")
                        print(img_slider)
                        print(e)
                        continue
                ################################################################

                print("{}已經操作完畢".format(url))
            except Exception as e:
                print("基本錯誤")
                print(e)

圖片最終的JSON已經拿到,最後一步,下載圖片,噹噹噹~~~~,一頓迅猛的操作之後,圖片就拿下來了


async def fetch_img_url(num):
    # 程式碼去上面找
    async with aiohttp.ClientSession() as session:
        # 獲取輪播圖地址
        async with session.get(url,headers=headers) as response:
            try:
                # 程式碼去上面找
                for img_slider in urls:
                    try:
                        async with session.get(img_slider, headers=headers) as slider:
                            # 程式碼去上面找
                            ##########################################################
                            for img in pic_json:
                                try:
                                    img = img["downloadPic"]
                                    async with session.get(img, headers=headers) as img_res:
                                        imgcode = await img_res.read()  # 圖片讀取
                                        with open("images/{}".format(img.split('/')[-1]), 'wb') as f:
                                            f.write(imgcode)
                                            f.close()
                                except Exception as e:
                                    print("圖片下載錯誤")
                                    print(e)
                                    continue
                            ###############################################################

                    except Exception as e:
                        print("獲取圖片列表錯誤")
                        print(img_slider)
                        print(e)
                        continue
                print("{}已經操作完畢".format(url))
            except Exception as e:
                print("基本錯誤")
                print(e)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視訊,這裡是Python學習者的聚集地,零基礎,進階,都歡迎

圖片會在你提前寫好的images資料夾裡面快速的生成

tasks最多可以開1024協程,但是建議你開100個就OK了,太多併發,人家伺服器吃不消。

以上操作執行完畢,在新增一些細節,比如儲存到指定