python如何获取json数据最使用方法

在Python中获取JSON数据的主要方式有:利用requests库从API获取JSON数据、读取本地JSON文件。
最常用的方法是通过requests库来从API获取JSON数据,因为大多数Web服务和API都会返回JSON格式的数据。
接下来我将实例演示如何使用requests库从API获取JSON数据的两种方法

import urllib.request
import json
import requests
from collections import OrderedDict

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'
}
# 实例一:

# url = 'http://www.weather.com.cn/data/cityinfo/101050101.html'
# r= requests.get(url)
# html = r.content.decode('utf-8')
# dic = json.loads(html)
# we = dic['weatherinfo']
# print('城市:'+ we['city'])
# print('时间:'+we['ptime'])
# print('天气:'+we['weather'])
# print('最高温度:'+we['temp2'])
# print('最低温度:'+we['temp1'])

# 实例二:
url2 = 'http://www.zimuzu.tv/public/hotkeyword'
r2 = requests.get(url2, headers=headers)
html2 = r2.content.decode('utf-8')
dict = json.loads(html2, object_pairs_hook=OrderedDict)
u = []
for i in range(0, 10):
    k = dict['data'][i]['keyword']
    u.append(k)
print(u)

上面两个方式就是平时最常使用的python对接json的好办法,后期会更新其他方式,欢迎关注。

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容