主页 M

python读json实现控制下载速度爬bilibili小视频

2020-03-26 网页编程网 网页编程网
# -*- coding: utf-8 -*-
"""
从排行流入手,控制下载速度
"""
import requests
tag='今日热门'
offset=2#第几页,每页10
headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/82.0.4068.4 Safari/537.36'
        }
#1.请求
def Json():
    for i in range(0,offset+1):
        #url='https://api.vc.bilibili.com/board/v1/ranking/top?page_size=10&next_offset=&tag=%E4%BB%8A%E6%97%A5%E7%83%AD%E9%97%A8&platform=pc'
        if i>0:
            k=(i*10+1)
        else:
            k=''
        url='https://api.vc.bilibili.com/board/v1/ranking/top?page_size=10&next_offset={}&tag={}&platform=pc'.format(k,tag)

        response=requests.get(url).json()
        data=response['data']['items']#{}号像桶一样取其值
        for i in data:
            item=i['item']
            videoId=i['item']['id']
            videoURL=item['video_playurl']
            Down(videoId,videoURL)

#2.提取视频下载并保存
def Down(name,url):
    video_response=requests.get(url,headers=headers,stream=True)
    chunk_size=1024#防止爬的过快,设置最大流速度
    #文件读写,a文件追加(不要覆盖),w文件存在就写入,不存在就创建(覆盖),b进制文件读写
    with open('video/{}.mp4'.format(name),'ab') as f:
        for data in video_response.iter_content(chunk_size=chunk_size):
            f.write(data)
        print('{} downed'.format(name))

#防止显露源码
if __name__=='__main__':
    Json()
阅读原文
阅读 3784
123 显示电脑版