Python基礎進階之海量表情包多線程爬蟲功能的實現(xiàn)
在我們?nèi)粘A奶斓倪^程中會使用大量的表情包,那么如何去獲取表情包資源呢?今天老師帶領大家使用python中的爬蟲去一鍵下載海量表情包資源
二、知識點requests網(wǎng)絡庫bs4選擇器文件操作多線程
三、所用到得庫import osimport requestsfrom bs4 import BeautifulSoup四、 功能
# 多線程程序需要用到的一些包# 隊列from queue import Queuefrom threading import Thread五、環(huán)境配置
解釋器 python3.6編輯器 pycharm專業(yè)版 激活碼
六、多線程類代碼# 多線程類class Download_Images(Thread): # 重寫構(gòu)造函數(shù) 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:# 當爬蟲程序執(zhí)行完成/出錯中斷之后發(fā)送消息給線程 代表線程必須停止執(zhí)行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多線程爬蟲內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. PHP設計模式中工廠模式深入詳解2. JSP數(shù)據(jù)交互實現(xiàn)過程解析3. .NET中l(wèi)ambda表達式合并問題及解決方法4. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題5. ThinkPHP5實現(xiàn)JWT Token認證的過程(親測可用)6. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明7. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法8. CSS hack用法案例詳解9. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)10. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向
