一、处理API响应
import requests
#API调用的url
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
#检验调用是否成功
print("Status code:",r.status_code)
返回200说明调用成功了,失败了好像是返回404,这可能是url输入错误导致
二、处理响应字典
代码如下(示例):
response_dict = r.json()#利用json将其转化为字典dict
print(response_dict.keys())#打印字典的键
repo_dicts = response_dict['items']
print("items length:{}".format(len(repo_dicts)))
print("total conut:{}".format(response_dict['total_count']))
返回的是一下结果:
dict_keys(['total_count', 'incomplete_results', 'items'])
items length:30
total conut:15184142
研究第一个仓库:
# 研究第一个项目
repo_dict = repo_dicts[0]
print("\nkey:",len(repo_dicts))
for key in repo_dict.keys():
print(key)
返回结果如下:
key: 30
id
node_id
name
full_name
private
owner
.....
三、使用pygal可视化仓库
import pygal
from pygal.style import LightStyle as LS,LightColorizedStyle as LCS
names = []
plot_dicts = []#用于储存每个仓库的自定义
for repo_dict in repo_dicts:
names.append(repo_dict['name'])
plot_dict = {'value':repo_dict['stargazers_count'],
'label':repo_dict['description'],
'xlink':repo_dict['html_url']}#在图表中添加可点击的链接
plot_dicts.append(plot_dict)
my_style = LS(base_style=LCS)
#以下是是一些图像改进
my_config = pygal.Config()
my_config.x_label_rotation =45#x轴标题字旋转45
my_config.show_legend = False#不展示图例
my_config.title_font_size = 24#设置标题字大小
my_config.label_font_size = 14#设置副标签字大小
my_config.major_label_font_size = 30#设置主标签字体大小(y轴上5000整数倍的刻度)
my_config.truncate_label = 15#如果x轴标题字大于15,会缩减键为15个字符,但是光标触碰时,会全部站显示出来
my_config.show_y_guides = False#取消横线
my_config.show_x_guides = False#取消竖线
my_config.width = 1000
chart = pygal.Bar(my_config,style = my_style)
#chart = pygal.Bar(style=my_style,x_label_rotation = 45,show_legend = False)
chart.title = 'most-starred python project'
chart.x_labels = names
chart.add('',plot_dicts)
chart.render_to_file('python_repos.svg')
返回结果为:
点击第一个图标时,因为设置了链接,所以会跳转到对应的网页:
参考书籍:
[1](美)埃里克·马瑟斯.Python编程 从入门到实践(第3版) 编程语言[M].人民邮电出版社,2023.
总结
使用API,可以方便我们去访问和分析信息。