python爬蟲如何獲取表情包
1、創(chuàng)建請求頭,也被稱為偽裝瀏覽器
如果不添加請求頭的話,可能會出現(xiàn)當(dāng)前網(wǎng)站沒有訪問權(quán)限。
2、使用requests 網(wǎng)絡(luò)請求庫完成網(wǎng)站數(shù)據(jù)請求
3、獲取數(shù)據(jù)后使用bs4對頁面數(shù)據(jù)進行提取
需要用到一個非常好用的第三方包:bs4。

實例
import os
import requests
from bs4 import BeautifulSoup
if not os.path.exists('./images/'):
os.mkdir('./images/')
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'
}
url = 'https://fabiaoqing.com/biaoqing/lists/page/1.html'
response = requests.get(url, headers=headers).text
'''
lxml: html解析庫,因為python和html兩者沒有關(guān)系
python沒有辦法直接控制html代碼
我們就需要使用lxml這個庫將html代碼轉(zhuǎn)成python對象
需要大家去下載 pip install lxml
'''
soup = BeautifulSoup(response, 'lxml')
img_list = soup.find_all('img', class_='ui image lazy')
for img in img_list:
img_url = img['data-original']
img_title = img['title']
print(img_url, img_title)
try:
with open('./images/' + img_title + os.path.splitext(img_url)[-1], 'wb') as f:
'''
因為一張圖片是二進制數(shù)據(jù)
如果我們使用text文本形式返回
會對文件造成破壞
使用content去返回原始數(shù)據(jù)
'''
image = requests.get(img_url, headers=headers).content
# 寫入二進制數(shù)據(jù) image這個變量是存儲requests返回的二進制數(shù)據(jù)的
f.write(image)
print('保存成功:', img_title)
except:
pass
以上就是python爬蟲獲取表情包的方法,希望對大家有所幫助。
搜索下方加老師微信
老師微信號:XTUOL1988【切記備注:學(xué)習(xí)Python】
領(lǐng)取Python web開發(fā),Python爬蟲,Python數(shù)據(jù)分析,人工智能等精品學(xué)習(xí)課程。帶你從零基礎(chǔ)系統(tǒng)性的學(xué)好Python!
*聲明:本文于網(wǎng)絡(luò)整理,版權(quán)歸原作者所有,如來源信息有誤或侵犯權(quán)益,請聯(lián)系我們刪除或授權(quán)
評論
圖片
表情



