基于python3的一次简单的请求url接口返回json类型结果实例。

#-*- coding: UTF-8 -*
from urllib import request
import json
import requests
import os
#获取每一页数据
def get_result_page(url):
    header = {'Accept-Charset': 'UTF-8',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'clientType': 'web',
            'clientVersion': '0.1.0',
            'Cookie': 'JSESSIONID=2032D8E562F3C8A84C72E5FA286541EC',
            'Host': 'web.rr.tv',
            'Origin': 'http://www.rrmj.tv',
            'Referer': 'http://www.rrmj.tv/',
            'User-Agent ': 'Mozilla/5.0 (Windows NT 10.0;WOW64;rv:61.0) Gecko/20100101 Firefox/61.0'}
    data = None
    rq = request.Request(url, data = data,headers = header)
    res = request.urlopen(rq);
    respoen = res.read();
    result = str(respoen, encoding = "utf-8")
    return result

#根据id下载视频到本地    
def get_video_by_id(id):
    url ='https://web.rr.tv/v3plus/video/getVideoPlayLinkByVideoId?videoId='+str(id)
    header = {'Accept-Charset': 'UTF-8',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'clientType': 'web',
            'clientVersion': '0.1.0',
            'Cookie': 'JSESSIONID=8804F16A013519D20FE2B3C7DA72BAC4',
            'Host': 'web.rr.tv',
            'Origin': 'http://www.rrmj.tv',
            'Referer': 'http://www.rrmj.tv/',
            'User-Agent ': 'Mozilla/5.0 (Windows NT 10.0;WOW64;rv:61.0) Gecko/20100101 Firefox/61.0'}
    data = None
    rq = request.Request(url, data = data,headers = header)
    res = request.urlopen(rq);
    respoen = res.read();
    result = str(respoen, encoding = "utf-8")
    cl = json.loads(result)
    #print(cl)
    #print(cl['code'])
    #print(cl['data']['playLink'])
    url = cl['data']['playLink']
    #print(url)
    r = requests.get(url)
    with open("C:/Users/Administrator/Desktop/rrsp/"+str(id)+".mp4", "wb") as code:
        code.write(r.content)
    
#获取请求结果
def get_data_json():
    url = 'https://web.rr.tv/v3plus/uper/videoList?userId=10373529&sort=playCount'
    result = get_result_page(url)
    js = json.loads(result);
    res = js['data']['results']
    print(len(res))
    for i in res:
       print(i['id'])
       result = os.path.exists("C:/Users/Administrator/Desktop/rrsp/"+str(i['id'])+".mp4")
       #print(result)
       if result == False:
           get_video_by_id(i['id'])
       
    
if __name__ == '__main__':
    get_data_json()

通过f12找到请求头

基于python3的一次简单的请求url接口返回json类型结果实例。_第1张图片

你可能感兴趣的:(Python)