爬取今日头条街拍数据,练习ajax数据爬取

今日头条街拍数据:

代码:

import requests
import json
import os
from urllib.request import urljoin
from urllib.parse import urlencode
from hashlib import md5



# 获取单页数据
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
    
# 解析单页数据
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__':
    # 使用进程池
    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()
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值