Python基礎進階之海量表情包多執行緒爬蟲功能的實現
阿新 • • 發佈:2020-12-18
一、前言
在我們日常聊天的過程中會使用大量的表情包,那麼如何去獲取表情包資源呢?今天老師帶領大家使用python中的爬蟲去一鍵下載海量表情包資源
二、知識點
requests網路庫
bs4選擇器
檔案操作
多執行緒
三、所用到得庫
import os import requests from bs4 import BeautifulSoup
四、 功能
# 多執行緒程式需要用到的一些包 # 佇列 from queue import Queue from threading import Thread
五、環境配置
直譯器 python3.6
編輯器 pycharm專業版 啟用碼
六、多執行緒類程式碼
# 多執行緒類 class Download_Images(Thread): # 重寫建構函式 def __init__(self,queue,path): Thread.__init__(self) # 類屬性 self.queue = queue self.path = path if not os.path.exists(path): os.mkdir(path) def run(self) -> None: while True: # 圖片資源的url連結地址 url = self.queue.get() try: download_images(url,self.path) except: print('下載失敗') finally: # 當爬蟲程式執行完成/出錯中斷之後傳送訊息給執行緒 代表執行緒必須停止執行 self.queue.task_done()
七、爬蟲程式碼
# 爬蟲程式碼 def download_images(url,path): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/84.0.4147.105 Safari/537.36' } response = requests.get(url,headers=headers) soup = BeautifulSoup(response.text,'lxml') img_list = soup.find_all('img',class_='ui image lazy') for img in img_list: image_title = img['title'] image_url = img['data-original'] try: with open(path + image_title + os.path.splitext(image_url)[-1],'wb') as f: image = requests.get(image_url,headers=headers).content print('正在儲存圖片:',image_title) f.write(image) print('儲存成功:',image_title) except: pass if __name__ == '__main__': _url = 'https://fabiaoqing.com/biaoqing/lists/page/{page}.html' urls = [_url.format(page=page) for page in range(1,201)] queue = Queue() path = './threading_images/' for x in range(10): worker = Download_Images(queue,path) worker.daemon = True worker.start() for url in urls: queue.put(url) queue.join() print('下載完成...')
八、爬取效果圖片
到此這篇關於Python基礎進階之海量表情包多執行緒爬蟲的文章就介紹到這了,更多相關Python多執行緒爬蟲內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!