本篇文章為大家展示了使用Python怎么實現一個多線程爬蟲功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
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 = '/tupian/20230522/{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怎么實現一個多線程爬蟲功能-創新互聯
當前地址:http://vcdvsql.cn/article28/ddjcjp.html
成都網站建設公司_創新互聯,為您提供App設計、關鍵詞優化、微信小程序、網站排名、Google、網站策劃
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯