通過(guò)本案例解析ajax請(qǐng)求返回的信息下載圖片
爬取url地址:https://pic.sogou.com/pics?query=動(dòng)物
分析:
分析url地址:每頁(yè)25條數(shù)據(jù),共計(jì)10頁(yè)
第1頁(yè):https://pic.sogou.com/napi/pc/searchList?mode=1&start=0&xml_len=48&query=動(dòng)物
第2頁(yè):https://pic.sogou.com/napi/pc/searchList?mode=1&start=48&xml_len=48&query=動(dòng)物
第3頁(yè):https://pic.sogou.com/napi/pc/searchList?mode=1&start=96&xml_len=48&query=動(dòng)物
通過(guò)分析得出請(qǐng)求改變start參數(shù)就可以改變頁(yè)數(shù)
具體實(shí)現(xiàn)代碼:
import requests
import os
class ImageSougou(object):
url = 'https://pic.sogou.com/napi/pc/searchList'
save_dir = './sougou' # 文件保存的路徑
count = 0
# 初始化
def __init__(self, word):
self.word = word
self.dir_path = os.path.join(self.save_dir, word)
self.params = {
'query': word,
'mode': '1',
'start': '0',
'xml_len': 48,
}
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
}
# 創(chuàng)建保存圖片的文件夾
self.folder_exist(self.dir_path)
self.last_img_url = ''
self.current_page = 0
# 請(qǐng)求包含圖片url的網(wǎng)頁(yè)
def parse(self):
while True:
self.params['start'] = str(self.current_page*48)
response = requests.get(url=self.url, headers=self.headers, params=self.params)
response.encoding='utf8'
data = response.json()['data']['items']
if data:
for img_info in data:
img_url = img_info['picUrl']
self.download(img_url)
self.current_page += 1
else:
break
# 下載一張圖片
def download(self, img_url, img_type='jpg'):
self.count += 1
print('正在下載第%d張圖片...'%self.count, img_url)
try:
response = requests.get(img_url)
except Exception as e:
print('下載失敗:', img_url)
return None
img_name = img_url.split('/')[-1]
img_path = os.path.join(self.dir_path, img_name)
try:
with open(img_path, 'wb') as f:
f.write(response.content)
except Exception as e:
print('下載失敗:', img_url)
def folder_exist(self, dir_path):
'''
1. 作用:判斷文件夾路徑是否存在,不存在則創(chuàng)建
2. 參數(shù):dir_path:文件夾路徑
3. 返回值:None
'''
if not os.path.exists(dir_path):
os.makedirs(dir_path)
if __name__ == '__main__':
image = ImageSougou('動(dòng)物')
image.parse()
審核編輯:符乾江
-
python
+關(guān)注
關(guān)注
56文章
4827瀏覽量
86804 -
爬蟲(chóng)
+關(guān)注
關(guān)注
0文章
83瀏覽量
7515
發(fā)布評(píng)論請(qǐng)先 登錄
FLIR ONE Edge Pro紅外熱像儀在爬寵飼養(yǎng)中的應(yīng)用
TRCX應(yīng)用:顯示面板電容指紋分析
流速儀檢定車同步電機(jī)調(diào)速的瞬態(tài)過(guò)程分析
新能源汽車驅(qū)動(dòng)電機(jī)專利信息分析
格陸博科技榮登投中信息2024年度銳公司100榜單
集成電路設(shè)計(jì)中靜態(tài)時(shí)序分析介紹
如何提高錫膏在焊接過(guò)程中的爬錫性?
什么是爬電距離與電氣間隙?

評(píng)論