通过分析ajax网页获取今日头条街拍美图
作者:互联网
首先解释下什么是ajax动态网页,刷微博会经常遇见这种,往下一直拉取,就会一直有数据在加载,然后显示在你的界面,类似于下图。
也能发现,该网页是通过改变offset(步长为20),来加载数据(观察改步是通过的XHR标签)
然后抓取数据。
有待学习google开发者F12
network
如果看ajax加载,需要XHR标签
如果看源码,需要Doc标签
待有机会,详细解析代码,目前只是崔老师的成功爬取的代码,有pool层
from requests.exceptions import RequestException
import json
import re
from bs4 import BeautifulSoup
import requests
from urllib.parse import urlencode
from requests import codes # ?from 和 import 的区别
import os
from hashlib import md5 # ?
from multiprocessing.pool import Pool # 多进程池
def get_page_index(offset, keyword):
data = {
'offsets': offset,
'format': 'json',
'keyword': keyword,
'autoload': 'true',
'count': '20',
'cur_tab': 3
}
url = 'http://www.toutiao.com/search_content/?' + urlencode(data) # 这是网页的地址,urlencode是url的一种编码方式
try:
response = requests.get(url)
if response.status_code == codes.ok:
return response.json()
except requests.ConnectionError:
print('请求索引出错')
return None
def get_images(json):
if json.get('data'):
data = json.get('data')
for item in data:
if item.get('cell_type') is not None:
continue
title = item.get('title')
images = item.get('image_list')
for image in images:
yield {
'image': 'https:' + image.get('url'),
'title': title
}
def save_image(item):
img_path = 'img' + os.path.sep + item.get('title')
if not os.path.exists(img_path):
os.makedirs(img_path)
try:
resp = requests.get(item.get('image'))
if codes.ok == resp.status_code:
file_path = img_path + os.path.sep + '{file_name}.{file_suffix}'.format(
file_name=md5(resp.content).hexdigest(),
file_suffix='jpg')
if not os.path.exists(file_path):
with open(file_path, 'wb') as f:
f.write(resp.content)
print('Downloaded image path is %s' % file_path)
else:
print('Already Downloaded', file_path)
except requests.ConnectionError:
print('Failed to Save Image,item %s' % item)
def main(offset):
json = get_page_index(offset,'街拍')
for item in get_images(json):
print(item)
save_image(item)
GROUP_START = 0
GROUP_END = 7
if __name__ == '__main__':
pool = Pool()
groups = ([x * 20 for x in range(GROUP_START,GROUP_END + 1)])
pool.map(main,groups) # 池化匹配
pool.close()
pool.join()
标签:file,get,image,item,ajax,美图,import,path,头条 来源: https://blog.csdn.net/ACBattle/article/details/84679828