标准获取API接口的json文件
import requests
import json
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
try:
r = requests.get(url)
except requests.exceptions.ConnectionError:
print('由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败')
else:
print(f"Status code: {r.status_code}")
response_dict = r.json()
readable_file = 'data/readable_hn_data.json' # 将要创建的文件名称
with open(readable_file, 'w') as f: # 写入文件
json.dump(response_dict, f, indent=4)
第一版本
import requests
from plotly.graph_objs import Bar
from plotly import offline
# 执行API调用并存储响应。
# 存储API调用的URL
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
# 最新的GitHub API版本为第3版,因此通过指定headers显式地要求使用这个版本的API
headers = {'Accept': 'application/vnd.github.v3+json'}
# 使用requests调用API,我们调用get()并将URL传递给它,再将响应对象赋给变量r
r = requests.get(url, headers=headers)
# 响应对象包含一个名为status_code的属性,指出了请求是否成功(状态码200表示请求成功)。打印status_code,核实调用是否成功
print(f"Status code: {r.status_code}")
# 处理结果。
# 这个API返回JSON格式的信息,因此使用方法json()将这些信息转换为一个Python字典,并将结果存储在response_dict中。
response_dict = r.json()
repo_dicts = response_dict['items']
repo_names, stars, labels = [], [], [] # 创建labels列表 装填项目所有者和描述
for repo_dict in repo_dicts:
repo_names.append(repo_dict['name']) # 提取项目名称
stars.append(repo_dict['stargazers_count']) # 提取星级
# 提取每个项目的所有者和描述 装填到labels列表中
owner = repo_dict['owner']['login'] # 提取每个项目的所有者
description = repo_dict['description'] # 提取每个项目的描述
label = f"{owner}<br />{description}" # 编辑一下项目和描述中间加换行符
labels.append(label)
# 可视化。
# 定义列表data。它像第16章的列表data一样包含一个字典,指定了图表的类型,并提供了x值和y值:x值为项目名称,y值为项目获得了多少个星。
data = [{
'type': 'bar',
'x': repo_names,
'y': stars,
'hovertext': labels, #添加鼠标悬停标签
'marker': {
'color': 'rgb(60,100,150)', # 条形指定为蓝色
'line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}, # 像素为1.5宽的深灰色外框
'opacity': 0.6, # 不透明度设置为0.6
},
}]
# 使用字典定义图表的布局。这里没有创建Layout实例,而是创建了一个包含布局规范的字典,并在其中指定了图表的名称以及每个坐标轴的标签。
my_layout = {
'title': 'GitHub上最受欢迎的Python项目',
'titlefont': {'size': 28}, # 指定图表名称的字号
'xaxis': {'title': 'Repository',
'titlefont': {'size': 24}, # 指定轴标签字号的设置
'tickfont': {'size': 14}, # 刻度标签字号的设置
},
'yaxis': {'title': 'Stars',
'titlefont': {'size': 24},
'tickfont': {'size': 14},
},
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='python_repos.html')
第二版本(增加了超链接):
import requests
from plotly.graph_objs import Bar
from plotly import offline
# 执行API调用并存储响应。
# 存储API调用的URL
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
# 最新的GitHub API版本为第3版,因此通过指定headers显式地要求使用这个版本的API
headers = {'Accept': 'application/vnd.github.v3+json'}
# 使用requests调用API,我们调用get()并将URL传递给它,再将响应对象赋给变量r
r = requests.get(url, headers=headers)
# 响应对象包含一个名为status_code的属性,指出了请求是否成功(状态码200表示请求成功)。打印status_code,核实调用是否成功
print(f"Status code: {r.status_code}")
# 处理结果。
# 这个API返回JSON格式的信息,因此使用方法json()将这些信息转换为一个Python字典,并将结果存储在response_dict中。
response_dict = r.json()
repo_dicts = response_dict['items'] # 将json文件中的item键值取出到repo_dicts,下面将遍历这个字典取值
# repo_names, stars, labels = [], [], [] # 创建labels列表 装填项目所有者和描述
repo_links, stars, labels = [], [], []
for repo_dict in repo_dicts:
# repo_names.append(repo_dict['name']) # 提取项目名称
repo_name = repo_dict['name'] # 提取项目名称,本次这样写是为了增加超链接
repo_url = repo_dict['html_url'] # 提取项目的url网址
repo_link = f"<a href='{repo_url}'>{repo_name}</a>" # 拼接href超链接
repo_links.append(repo_link) # 将拼接好的超链接 追加到 repo_links 列表中
stars.append(repo_dict['stargazers_count']) # 提取星级
# 提取每个项目的所有者和描述 装填到labels列表中
owner = repo_dict['owner']['login'] # 提取每个项目的所有者
description = repo_dict['description'] # 提取每个项目的描述
label = f"{owner}<br />{description}" # 编辑一下项目和描述中间加换行符
labels.append(label)
# 可视化。
# 定义列表data。它像第16章的列表data一样包含一个字典,指定了图表的类型,并提供了x值和y值:x值为项目名称,y值为项目获得了多少个星。
data = [{
'type': 'bar',
'x': repo_links,
'y': stars,
'hovertext': labels, # 添加鼠标悬停标签
'marker': {
'color': 'rgb(60,100,150)', # 条形指定为蓝色
'line': {'width': 1.5, 'color': 'rgb(25, 25, 25)'}, # 像素为1.5宽的深灰色外框
'opacity': 0.6, # 不透明度设置为0.6
},
}]
# 使用字典定义图表的布局。这里没有创建Layout实例,而是创建了一个包含布局规范的字典,并在其中指定了图表的名称以及每个坐标轴的标签。
my_layout = {
'title': 'GitHub上最受欢迎的Python项目',
'titlefont': {'size': 28}, # 指定图表名称的字号
'xaxis': {'title': 'Repository',
'titlefont': {'size': 24}, # 指定轴标签字号的设置
'tickfont': {'size': 14}, # 刻度标签字号的设置
},
'yaxis': {'title': 'Stars',
'titlefont': {'size': 24},
'tickfont': {'size': 14},
},
}
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='python_repos.html')
第三版本(针对每一篇文章都适用一次API调用)
from operator import itemgetter
import requests
# 执行API调用并存储响应。
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")
# 处理有关每篇文章的信息。
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
# 对于每篇文章,都执行一个API调用。
url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
r = requests.get(url)
print(f"id: {submission_id}\tstatus: {r.status_code}")
response_dict = r.json()
# 对于每篇文章,都创建一个字典。
submission_dict = {
'title': response_dict['title'],
'hn_link': f"http://news.ycombinator.com/item?id={submission_id}",
'comments': response_dict['descendants'],
}
submission_dicts.append(submission_dict)
# 根据submission_dicts列表中的comments 键值 来进行降序排序 , 用到了operator的itemgetter函数
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), reverse=True)
for submission_dict in submission_dicts:
print(f"\nTitle: {submission_dict['title']}")
print(f"Discussion link: {submission_dict['hn_link']}")
print(f"Comments: {submission_dict['comments']}")