Python基礎進階之海量表情包多線程爬蟲功能的實現
在我們日常聊天的過程中會使用大量的表情包,那么如何去獲取表情包資源呢?今天老師帶領大家使用python中的爬蟲去一鍵下載海量表情包資源
二、知識點requests網絡庫bs4選擇器文件操作多線程
三、所用到得庫import osimport requestsfrom bs4 import BeautifulSoup四、 功能
# 多線程程序需要用到的一些包# 隊列from queue import Queuefrom 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).contentprint(’正在保存圖片:’, image_title)f.write(image)print(’保存成功:’, image_title) except: passif __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多線程爬蟲內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: