
這篇文章主要介紹了Python基礎(chǔ)進(jìn)階之海量表情包多線程爬蟲,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
一、前言
在我們?nèi)粘A奶斓倪^程中會(huì)使用大量的表情包,那么如何去獲取表情包資源呢?今天老師帶領(lǐng)大家使用python中的爬蟲去一鍵下載海量表情包資源
二、知識(shí)點(diǎn)
requests網(wǎng)絡(luò)庫(kù)
bs4選擇器
文件操作
多線程
三、所用到得庫(kù)
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)階之海量表情包多線程爬蟲的文章就介紹到這了

掃下方二維碼加老師微信
或是搜索老師微信號(hào):XTUOL1988【切記備注:學(xué)習(xí)Python】
領(lǐng)取Python web開發(fā),Python爬蟲,Python數(shù)據(jù)分析,人工智能等學(xué)習(xí)教程。帶你從零基礎(chǔ)系統(tǒng)性的學(xué)好Python!
也可以加老師建的Python技術(shù)學(xué)習(xí)教程qq裙:245345507,二者加一個(gè)就可以!
歡迎大家點(diǎn)贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
萬(wàn)水千山總是情,點(diǎn)個(gè)【在看】行不行
*聲明:本文于網(wǎng)絡(luò)整理,版權(quán)歸原作者所有,如來(lái)源信息有誤或侵犯權(quán)益,請(qǐng)聯(lián)系我們刪除或授權(quán)事宜