02.28 Python多線程threading—圖片下載

上一篇,寫了一個爬壁紙圖片的小爬蟲:Python爬蟲入門—圖片下載下載效果太慢了,於是乎想到了用多線程改造一下,看看速度能提高多少!

雖然說,由於GIL鎖(Global Interpreter Lock)的存在,Python的多線程不是真正意義上的多線程,一個時間段內,一個CPU只能執行一個線程。但是在爬蟲相關的程序上,經常出現IO密集型任務多CPU密集型任務少的情況,大多數時間都在等get、post請求、收發數據(對於本次的爬蟲圖片下載程序,更是如此)。於是可以用Python的多線程來實現加速,即一個線程在get、post或等數據傳輸時,不必停止整個程序,而是切換到其他的線程完成接下來的任務。這樣,本質上單線程的Python也能實現多線程的效果~

  • 關於多進程和多線程,牆裂推薦廖雪峰的:進程和線程​
  • https://www.liaoxuefeng.com/wiki/1016959663602400/1017627212385376
  • 還有這篇文章:《從0到1,Python異步編程的演進之路》
  • https://zhuanlan.zhihu.com/p/33816013

我們以關鍵詞‘pig’為例,可以搜到77張相關圖片,然後,讓我們來做一下對比測試,比較下原始單線程代碼和多線程代碼下載速度的差異~

改造前,單線程的代碼如下:

<code>#_*_ coding:utf-8 _*_#__author__='陽光流淌007'#__date__2018-01-21'#爬取wallhaven上的的圖片,支持自定義搜索關鍵詞,自動爬取並該關鍵詞下所有圖片並存入本地電腦。import osimport requestsimport timeimport randomfrom lxml import etreekeyWord = input(f"{'Please input the keywords that you want to download :'}")class Spider():    #初始化參數    def __init__(self):        #headers是請求頭,"User-Agent"、"Accept"等字段可通過谷歌Chrome瀏覽器查找!        self.headers = {        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36",        }        #filePath是自定義的,本次程序運行後創建的文件夾路徑,存放各種需要下載的對象。        self.filePath = ('/users/zhaoluyang/小Python程序集合/桌面壁紙/'+ keyWord + '/')    def creat_File(self):        #新建本地的文件夾路徑,用於存儲網頁、圖片等數據!        filePath = self.filePath        if not os.path.exists(filePath):            os.makedirs(filePath)    def get_pageNum(self):        #用來獲取搜索關鍵詞得到的結果總頁面數,用totalPagenum記錄。由於數字是夾在形如:1,985 Wallpapers found for “dog”的string中,        #所以需要用個小函數,提取字符串中的數字保存到列表numlist中,再逐個拼接成完整數字。。。        total = ""        url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc").format(keyWord)        html = requests.get(url)        selector = etree.HTML(html.text)        pageInfo = selector.xpath('//header[@class="listing-header"]/h1[1]/text()')        string = str(pageInfo[0])        numlist = list(filter(str.isdigit,string))        for item in numlist:            total += item        totalPagenum = int(total)        return totalPagenum    def main_fuction(self):        #count是總圖片數,times是總頁面數        self.creat_File()        count = self.get_pageNum()        print("We have found:{} images!".format(count))        times = int(count/24 + 1)        j = 1        start = time.time()        for i in range(times):            pic_Urls = self.getLinks(i+1)            start2 = time.time()            for item in pic_Urls:                self.download(item,j)                j += 1            end2 = time.time()            print('This page cost:',end2 - start2,'s')        end = time.time()        print('Total cost:',end - start,'s')    def getLinks(self,number):        #此函數可以獲取給定numvber的頁面中所有圖片的鏈接,用List形式返回        url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc&page={}").format(keyWord,number)        try:            html = requests.get(url)            selector = etree.HTML(html.text)            pic_Linklist = selector.xpath('//a[@class="jsAnchor thumb-tags-toggle tagged"]/@href')        except Exception as e:            print(repr(e))        return pic_Linklist    def download(self,url,count):        #此函數用於圖片下載。其中參數url是形如:https://alpha.wallhaven.cc/wallpaper/616442/thumbTags的網址        #616442是圖片編號,我們需要用strip()得到此編號,然後構造html,html是圖片的最終直接下載網址。        string = url.strip('/thumbTags').strip('https://alpha.wallhaven.cc/wallpaper/')        html = 'http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-' + string + '.jpg'        pic_path = (self.filePath + keyWord + str(count) + '.jpg' )        try:            start = time.time()            pic = requests.get(html,headers = self.headers)            f = open(pic_path,'wb')            f.write(pic.content)            f.close()            end = time.time()            print(f"Image:{count} has been downloaded,cost:",end - start,'s')        except Exception as e:            print(repr(e))spider = Spider()spider.main_fuction()/<code> 

下載77張圖片總耗時157.17749691009521 s

Python多線程threading—圖片下載

引入threading多線程模塊後的程序代碼如下:

<code>#_*_ coding:utf-8 _*_#__author__='陽光流淌007'#__date__='2018-01-28'#爬取wallhaven上的的圖片,支持自定義搜索關鍵詞,自動爬取並該關鍵詞下所有圖片並存入本地電腦。import osimport requestsimport timefrom lxml import etreefrom threading import ThreadkeyWord = input(f"{'Please input the keywords that you want to download :'}")class Spider():    #初始化參數    def __init__(self):        self.headers = {#headers是請求頭,"User-Agent"、"Accept"等字段可通過谷歌Chrome瀏覽器查找!        "User-Agent": "Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1",        }        self.proxies = {#代理ip,當網站限制ip訪問時,需要切換訪問ip"http": "http://61.178.238.122:63000",    }        #filePath是自定義的,本次程序運行後創建的文件夾路徑,存放各種需要下載的對象。        self.filePath = ('/users/zhaoluyang/小Python程序集合/桌面壁紙/'+ keyWord + '/')    def creat_File(self):        #新建本地的文件夾路徑,用於存儲網頁、圖片等數據!        filePath = self.filePath        if not os.path.exists(filePath):            os.makedirs(filePath)    def get_pageNum(self):        #用來獲取搜索關鍵詞得到的結果總頁面數,用totalPagenum記錄。由於數字是夾在形如:1,985 Wallpapers found for “dog”的string中,        #所以需要用個小函數,提取字符串中的數字保存到列表numlist中,再逐個拼接成完整數字。。。        total = ""        url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc").format(keyWord)        html = requests.get(url,headers = self.headers,proxies = self.proxies)        selector = etree.HTML(html.text)        pageInfo = selector.xpath('//header[@class="listing-header"]/h1[1]/text()')        string = str(pageInfo[0])        numlist = list(filter(str.isdigit,string))        for item in numlist:            total += item        totalPagenum = int(total)        return totalPagenum    def main_fuction(self):        #count是總圖片數,times是總頁面數        self.creat_File()        count = self.get_pageNum()        print("We have found:{} images!".format(count))        times = int(count/24 + 1)        j = 1        start = time.time()        for i in range(times):            pic_Urls = self.getLinks(i+1)            start2 = time.time()            threads = []            for item in pic_Urls:                t = Thread(target = self.download, args = [item,j])                t.start()                threads.append(t)                j += 1            for t in threads:                t.join()            end2 = time.time()            print('This page cost:',end2 - start2,'s')        end = time.time()        print('Total cost:',end - start,'s')    def getLinks(self,number):        #此函數可以獲取給定numvber的頁面中所有圖片的鏈接,用List形式返回        url = ("https://alpha.wallhaven.cc/search?q={}&categories=111&purity=100&sorting=relevance&order=desc&page={}").format(keyWord,number)        try:            html = requests.get(url,headers = self.headers,proxies = self.proxies)            selector = etree.HTML(html.text)            pic_Linklist = selector.xpath('//a[@class="jsAnchor thumb-tags-toggle tagged"]/@href')        except Exception as e:            print(repr(e))        return pic_Linklist    def download(self,url,count):        #此函數用於圖片下載。其中參數url是形如:https://alpha.wallhaven.cc/wallpaper/616442/thumbTags的網址        #616442是圖片編號,我們需要用strip()得到此編號,然後構造html,html是圖片的最終直接下載網址。        string = url.strip('/thumbTags').strip('https://alpha.wallhaven.cc/wallpaper/')        html = 'http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-' + string + '.jpg'        pic_path = (self.filePath + keyWord + str(count) + '.jpg' )        try:            start = time.time()            pic = requests.get(html,headers = self.headers)            f = open(pic_path,'wb')            f.write(pic.content)            f.close()            end = time.time()            print(f"Image:{count} has been downloaded,cost:",end - start,'s')        except Exception as e:            print(repr(e))spider = Spider()spider.main_fuction()/<code>

下載77張圖片總耗時23.993554830551147 s

Python多線程threading—圖片下載

對比一下,77張圖片的下載時間從157.17s變為23.99s,快了超過6倍。僅僅是簡單的改造,多線程對比單線程的提升還是很明顯的,其實還可以自己改寫多線程算法,還可以加上多進程充分利用CPU數量,還可以用異步協程處理,總之,還有很多可以優化的空間~


分享到:


相關文章: