Ajax动态爬取今日头条

 
import os
import requests
from urllib.parse import urlencode
from hashlib import md5
from multiprocessing.pool import Pool

GROUP_START = 1
GROUP_END = 5


def get_page(offset):
    params = {
        'offset': offset,#offset为设置的页数
        'format': 'json',
        'keyword': '街拍',
        'autoload': 'true',
        'count': '20',
        'cur_tab': '3',
        'from': 'gallery',
    }
    url = 'https://www.toutiao.com/search_content/?' + urlencode(params)
# urlencode函数的作用为将字典params为offset=0&format=json&keyword=%E8%A1%97%E6%8B%8D&autoload=true&count=20&cur_tab=1&from=search_tab

    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.json() #转化为json格式
    except requests.ConnectionError:
        return None
#将url解析

def get_images(json):
    data = json.get('data')#搜索键名为data的数据
    if data:
        for item in data:#data为list类型 item为字典类型
            # print(item)
            image_list = item.get('image_list')#将图片的连接整理出来
            title = item.get('title')#标题
            # print(image_list)
            if image_list:
                for image in image_list:
                    yield {
                        'image': image.get('url'),#将图片的链接取出来
                        'title': title
                    }


def save_image(item):
    if not os.path.exists(item.get('title')):#判断是否有此标题的文件,若没有则建立
        os.mkdir(item.get('title'))#建立一级目录 名为标题
    try:
        local_image_url = item.get('image')
        new_image_url = local_image_url.replace('list','large')#replace函数为替换函数将字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串 list换large根据结果来看是将图片放大了
        response = requests.get('http:' + new_image_url)#进入图片的链接
        if response.status_code == 200:
            file_path = '{0}/{1}.{2}'.format(item.get('title'), md5(response.content).hexdigest(), 'jpg')#将图片的名字进行格式化
            if not os.path.exists(file_path):
                with open(file_path, 'wb')as f:
                    f.write(response.content)#图片的存储
            else:
                print('Already Downloaded', file_path)
    except requests.ConnectionError:
        print('Failed to save image')


def main(offset):
    json = get_page(offset)#将链接导入并转化为json格式
    for item in get_images(json):
        print(item)
        save_image(item)


if __name__ == '__main__':
    pool = Pool()
    groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
    pool.map(main, groups)
    pool.close()#多线程

 爬取动态页面与正常的爬去没有太大的区别

但是要整理的数据实在太多了

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值