本篇文章给大家分享的是有关使用Ajax请求怎么爬取今日头条,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
代码如下:
import requests
import os
from urllib.parse import urlencode
from hashlib import md5
from multiprocessing.pool import Pool
from requests import codes
def get_page(offset):
params = {
"offset":offset,
"format":"json",
"keyword":"街拍",
"autoload":"true",
"count":"20",
"cur_tab":"1",
"from":"search_tab"
}
url = 'https://www.toutiao.com/search_content/?'+urlencode(params)
try:
response = requests.get(url)
if response.status_code == 200:
# print(url)
return response.json()
except requests.ConnectionError:
return None
# get_page(0)
def get_images(json):
if json.get('data'):
for item in json.get('data'):
if item.get('cell_type') is not None:
continue
title = item.get('title')
images = item.get('image_list')
for image in images:
yield {
'title':title,
'image':'https:' + image.get('url'),
}
def save_image(item):
#os.path.sep 路径分隔符‘//'
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'))
# print(type(resp))
if codes.ok == resp.status_code:
file_path = img_path + os.path.sep + '{file_name}.{file_suffix}'.format(
file_name=md5(resp.content).hexdigest(),#md5是一种加密算法获取图片的二进制数据,以二进制形式写入文件
file_suffix='jpg')
if not os.path.exists(file_path):
with open(file_path,'wb')as f:
f.write(resp.content)
print('Downladed 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(offset)
for item in get_images(json):
print(item)
save_image(item)
GROUP = 0
GROUP_END = 2
if __name__ == '__main__':
pool = Pool()
groups = ([x*20 for x in range(GROUP,GROUP_END)])
pool.map(main,groups) #将groups一个个调出来传给main函数
pool.close()
pool.join() #保证子进程结束后再向下执行 pool.join(1) 等待一秒
以上就是使用Ajax请求怎么爬取今日头条,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.jb51.net/article/149142.htm