Python基礎(chǔ)進(jìn)階之海量表情包多線程爬蟲功能的實(shí)現(xiàn)
一、前言
在我們?nèi)粘A奶斓倪^程中會(huì)使用大量的表情包,那么如何去獲取表情包資源呢?今天老師帶領(lǐng)大家使用python中的爬蟲去一鍵下載海量表情包資源
二、知識點(diǎn)
requests網(wǎng)絡(luò)庫
bs4選擇器
文件操作
多線程
三、所用到得庫
import os import requests from bs4 import BeautifulSoup
四、 功能
# 多線程程序需要用到的一些包 # 隊(duì)列 from queue import Queue from 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:
# 當(dāng)爬蟲程序執(zhí)行完成/出錯(cuò)中斷之后發(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).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('下載完成...')
八、爬取效果圖片

到此這篇關(guān)于Python基礎(chǔ)進(jìn)階之海量表情包多線程爬蟲的文章就介紹到這了,更多相關(guān)Python多線程爬蟲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python爬蟲框架Scrapy實(shí)戰(zhàn)之批量抓取招聘信息
網(wǎng)絡(luò)爬蟲又被稱為網(wǎng)頁蜘蛛,網(wǎng)絡(luò)機(jī)器人,在FOAF社區(qū)中間,更經(jīng)常的稱為網(wǎng)頁追逐者,是按照一定的規(guī)則,自動(dòng)抓取萬維網(wǎng)信息的程序或者腳本。這篇文章主要介紹Python爬蟲框架Scrapy實(shí)戰(zhàn)之批量抓取招聘信息,有需要的朋友可以參考下2015-08-08
使用Python對mongo數(shù)據(jù)庫中字符串型正負(fù)數(shù)值比較大小
這篇文章主要介紹了使用Python對mongo數(shù)據(jù)庫中字符串型正負(fù)數(shù)值比較大小,2023-04-04
python利用opencv實(shí)現(xiàn)SIFT特征提取與匹配
這篇文章主要為大家詳細(xì)介紹了python利用opencv實(shí)現(xiàn)SIFT特征提取與匹配,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
Python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫的代碼實(shí)例
今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)圖片轉(zhuǎn)字符畫的代碼實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02
Python中的異常處理相關(guān)語句基礎(chǔ)學(xué)習(xí)筆記
這里我們簡單整理一下Python中的異常處理相關(guān)語句基礎(chǔ)學(xué)習(xí)筆記,包括try...except與assert等基本語句的用法講解:2016-07-07

