通过调用api可以得到网站上实时的数据并显示出来。这里以github上的数据为例,得到star最多的ruby应用并通过柱状图显示数据结果
首先看效果
从图上可以看出,最多的是rails,通过图表显示,直观又方便。
代码如下:
import requests
import pygal
from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS
url = 'https://api.github.com/search/repositories?q=language:ruby&sort=stars'
r = requests.get(url)
if r.status_code == 200:
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
repo_dicts = response_dict['items']
names, stars = [], []
print("Repositories returned:", len(repo_dicts))
# 显示第一个信息
# repo_dict = repo_dicts[0]
# print("\nkeys:",len(repo_dict))
# print("name:", repo_dict['name'])
# print("owner:", repo_dict['owner']['login'])
for repo_dict in repo_dicts:
print('\nname:', repo_dict['name'])
print("owner:", repo_dict['owner']['login'])
print("Stars:", repo_dict['stargazers_count'])
print("Des:", repo_dict['description'])
names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
my_style = LS("#113366", base_style=LCS)
my_config = pygal.Config()
my_config.x_label_rotation = 45
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
my_config.major_label_font_size = 18
my_config.truncate_label = 15
my_config.show_y_guides = False
my_config.width = 1000
chart = pygal.Bar(my_config, style=my_style)
chart.title = 'Most-Starred python projects'
chart.x_labels = names
chart.add('', stars)
chart.render_to_file('python_repos.svg')
else:
print("Get data error.")