1. 程式人生 > >[Python爬蟲]爬蟲例項:爬取PEXELS圖片---修改為多程序爬蟲

[Python爬蟲]爬蟲例項:爬取PEXELS圖片---修改為多程序爬蟲

第二次修改的地址---->爬蟲例項:爬取PEXELS圖片—解決非同步載入問題
在前面的修改中,我們通過使用逆向工程成功解決了非同步載入的問題.但同時還有一個問題:效率問題,受限於網速,假如使用單程序下載圖片時下載的速度沒有佔滿,而使用多個程序時下載速度能夠佔滿的話,那麼多程序爬蟲在爬取圖片就具有更高的爬取效率.
但是,一個更直接體現出多程序爬蟲效率的測試是,我們只爬取圖片的下載連結而不進行下載,這樣就網速的影響就不會太大了.

Python的多執行緒和多程序

大家可能都聽過一點就是:python的多執行緒在同一時刻只會有一條執行緒跑在CPU裡面,其他執行緒都在睡覺。這是真的,至於問為什麼的話百度即可.
但是多程序就不同了,Python提高執行效率的方法是多程序.同一時刻,只有一個程序會被CPU排程,這就是單程序爬蟲

,但是通過使用multiprocessing庫,對於多核CPU,就可以輕鬆地轉換為多程序爬蟲併發執行多個爬蟲,也就是一個核可以跑一個爬蟲.

爬蟲測試

import requests
import re
import time
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                  'AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/67.0.3396.79 Safari/537.36'
}
def
pic_scratch(url): res = requests.get(url, headers) links = re.findall('<a href=\"(.*)\" download>', res.text)

使用單程序爬蟲時:

if __name__ == '__main__':
    start_time = time.time()
    urls = ['https://www.pexels.com/search/cat/?page=={}'.format(i) for i in range(1, 26)]
    for url in urls:
pic_scratch(url) end_time = time.time() print("總用時:", end_time - start_time)

在這裡插入圖片描述
使用多程序爬蟲時:(4個程序)

if __name__ == '__main__':
    start_time = time.time()
    urls = ['https://www.pexels.com/search/cat/?page=={}'.format(i) for i in range(1, 26)]
    pool = Pool(processes=4)
    pool.map(pic_scratch, urls)
    end_time = time.time()
    print("總用時:", end_time - start_time)

在這裡插入圖片描述
可見多程序對爬取速度的提升是非常可觀.
但是如果不僅爬取連結並且要下載的話,爬蟲完成的速度就要取決於自己的網速了…
最後貼一下完整程式碼…

爬蟲程式碼

import requests
import re
import time
from multiprocessing import Pool

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                  'AppleWebKit/537.36 (KHTML, like Gecko) '
                  'Chrome/67.0.3396.79 Safari/537.36'
}


def pic_scratch(url):
    res = requests.get(url, headers)
    links = re.findall('<a href=\"(.*)\" download>', res.text)
    for link in links:
        pic = requests.get(link, headers)
        pic_name = re.search('(?<=dl=).*\.jpg', link).group()
    with open('d:/cat/' + pic_name, 'wb') as pf:
        pf.write(pic.content)
    print("完成圖片下載:" + pic_name)


if __name__ == '__main__':
    start_time = time.time()
    urls = ['https://www.pexels.com/search/cat/?page=={}'.format(i) for i in range(1, 26)]
    pool = Pool(processes=4)
    pool.map(pic_scratch, urls)
    end_time = time.time()
    print("總用時:", end_time - start_time)