今日頭條街拍數(shù)據(jù):
- 獲取頁面:https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D的頁面中的ajax加載的數(shù)據(jù)。經(jīng)過分析頁面時(shí)數(shù)據(jù)流的形式展現(xiàn)數(shù)據(jù),在瀏覽器 F12 - Network選項(xiàng) - XHR中查看到ajax的請(qǐng)求信息,其中 request url為:
- https://www.toutiao.com/search_content/?offset=40&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=1&from=search_tab
- offset 參數(shù)代表了數(shù)據(jù)的分頁,數(shù)據(jù)時(shí) json 類型
- 解析數(shù)據(jù)目標(biāo):
- title : 標(biāo)題名
- image_list : 圖片url列表
- 存儲(chǔ)方式:以標(biāo)題為文件夾名,將圖片下載至該文件夾中。
代碼:
import requests
import json
import os
from urllib.request import urljoin
from urllib.parse import urlencode
from hashlib import md5
# 獲取單頁數(shù)據(jù)
def getOnePage(offset):
data = {
'offset': offset,
'format': 'json',
'keyword': '街拍',
'autoload': 'true',
'count': '20',
'cur_tab': '1',
'from': 'search_tab',
}
try:
url = 'https://www.toutiao.com/search_content/?' + urlencode(data)
response = requests.get(url)
if response.status_code == requests.codes.ok:
return response.json()
except Exception as f:
print(f)
return None
# 解析單頁數(shù)據(jù)
def parseOnePage(content):
if content.get('data'):
for item in content.get('data'):
title = item.get('title')
if title is not None:
imgList = item.get('image_list')
for imgUrl in imgList:
yield {
'title': title,
'imgUrl': 'http:'+imgUrl.get('url')
}
# 下載圖片
def downloadImg(item):
if not os.path.exists(item.get('title')):
os.mkdir(item.get('title'))
try:
response = requests.get(item.get('imgUrl'))
print(response.status_code)
if response.status_code == requests.codes.ok:
fileName = md5(response.content).hexdigest() + '.jpg'
filePath = os.path.join(item.get('title'),fileName)
if not os.path.exists(filePath):
with open(filePath, 'wb') as f:
f.write(response.content)
else:
print('file already Download', filePath)
except Exception as e:
print('file download failed!', item.get('imgUrl'))
def main(offset):
content = getOnePage(offset)
for item in parseOnePage(content):
downloadImg(item)
if __name__ == '__main__':
# 使用進(jìn)程池
from multiprocessing.pool import Pool
pool = Pool()
GROUP_START = 1
GROUP_END = 20
groups = ([i*20 for i in range(GROUP_START, GROUP_END+1)])
pool.map(main, groups)
pool.close()
pool.join()