Python使用API自动请求GitHub信息并使用Pygal将信息进行可视化

使用Web应用编程接口(API)自动请求网站的特定信息,在对这些信息进行可视化!!

Web API是网站的一部分,请求特定信息的程序交互,成为API调用,请求的数据以易于处理的格式(如JSON或CSV)返回。

1、使用API调用请求数据

  1. 本节内容可视化基于来自GitHub的信息(是一个分布式版本控制系统),GitHub上的项目都存储在仓库中
  2. 仓库中包含与项目相关的一切:代码、项目参与者信息、问题或bug报告等。
  3. 对于喜欢的项目,GitHub用户可给它加星(star)以表示支持,本节将编写程序,自动下载GitHub上星级最高的Python项目的信息,并对这些信息进行可视化处理。
1.1、API请求GitHub托管了多少python项目及最受欢迎的Python仓库信息

1、首先我们登入网站查看下 https://github.com/
在这里插入图片描述
2、在浏览器中输入如下地址:
https://api.github.com/search/repositories?q=language:python&sort=stars
https://api.github.com/
将请求发送到GitHub网站中响应API调用的部分
search/repositories
让API搜索GitHub上所有仓库
?q=language:python&sort=stars
问号指出我们要传递一个实参
q表示查询,获取语言为Python的仓库信息
sort=stars将项目按其获得的星级进行排序
效果图如下所示:
从第二行输出可知,GitHub总共有5010524个Python项目
在这里插入图片描述

1.2、安装requests

1、在pycharm终端中Terminal中输入pip install --user requests,报错说缺少urllib3库
在这里插入图片描述
2、查询下是否有urllib3,输入pip list,发现没有
在这里插入图片描述
3、安装urllib3输入pip install urllib3,Successfully 成功
在这里插入图片描述
4、再次输入pip install --user requests安装requests
在这里插入图片描述
5、输入pip list,查询发现有了requests,这时候安装完毕
在这里插入图片描述

2、处理API响应

编写程序,执行API调用并处理结果,找出GitHub上星级最高的Python项目

新建python_repos.py文件

import requests     #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典

#处理结果
print(response_dict.keys())     #打印主键

效果如下所示:
在这里插入图片描述
和请求的数据中一致
在这里插入图片描述

3、处理响应字典

将API调用返回的信息存储到字典后,我们就可以处理这个字典中的数据

3.1、获取仓库信息

在python_repos.py文件中修改:

import requests     #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
print("Repositories returned:",len(repo_dicts))

#研究第一个仓库
repo_dict=repo_dicts[0]
print("\nKeys:",len(repo_dict))
for key in sorted(repo_dict.keys()):
    print(key)
#处理结果
#print(response_dict.keys())     #打印主键

#探索有关仓库信息
将字典存入repo_dicts,通过len()获取仓库数量
#研究第一个仓库
打印第一个仓库键数,并遍历打印所有键
效果图如下
在这里插入图片描述

3.2、获取第一个仓库中的键和对应的值

在3.1中我们获取到repo_dict共包含70个键

在python_repos.py文件中修改:

import requests     #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
print("Repositories returned:",len(repo_dicts))

#研究第一个仓库
repo_dict=repo_dicts[0]
#print("\nKeys:",len(repo_dict))
#for key in sorted(repo_dict.keys()):
    #print(key)
print("\nSelected information about first repository:")
print('Name:',repo_dict['name'])		#项目名称
print('owner:',repo_dict['owner']['login'])		#登录名
print('Stars:',['stargazers_count'])				#该项目获得的星级
print('Repository:',repo_dict['html_url'])			#该项目的URL
print('Created:',repo_dict['created_at'])			#显示项目创建时间
print('Updated:',repo_dict['updated_at'])			#最后一次更新时间
print('Description:',repo_dict['description'])		#仓库描述
#处理结果
#print(response_dict.keys())     #打印主键

效果图如下:
在这里插入图片描述

4、概述最受欢迎的仓库

打印每个项目的名称、所有者、星级、在GitHub上的URL以及描述。

在python_repos.py文件中修改:

import requests     #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
print("Repositories returned:",len(repo_dicts))

print("\nSelected information about first repository:")
for repo_dict in repo_dicts:
    print('\nName:',repo_dict['name'])		#项目名称
    print('Qwner:',repo_dict['owner']['login'])		#登录名
    print('Stars:',['stargazers_count'])				#该项目获得的星级
    print('Repository:',repo_dict['html_url'])			#该项目的URL
    print('Description:',repo_dict['description'])		#仓库描述
#处理结果
#print(response_dict.keys())     #打印主键

效果图如下:
每个项目包含了我们需要的信息
在这里插入图片描述

5、监视API的速率限制

大多数API都存在速率限制,要获取是否接近GitHub的限制

在浏览器中输入:
https://api.github.com/rate_limit
新建test.py文件看下速率:

import requests     #导入模块requests

#执行API调用并存储响应
url='https://api.github.com/rate_limit'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功


#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print(response_dict['resources']['search'])

效果图如下:
显示极限为每分钟10个请求
在当前一分钟内还可以执行10个请求
在这里插入图片描述

6、使用Pygal可视化仓库

得到了我们需要的数据之后,我们可以进行可视化,呈现GitHub上Python项目的受欢迎程度

在python_repos.py文件中修改:

import requests     #导入模块requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))

names,stars=[],[]
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])		#项目名称
    stars.append(repo_dict['stargazers_count'])				#该项目获得的星级

#可视化
my_style=LS('#333366',base_style=LCS)
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
chart.title='Most-Starred Python Projects on GitHub'
chart.x_labels=names

chart.add('',stars)
chart.render_to_file('python_repos.svg')

names,stars=[],[]
建立两个空列表用来存储项目名和获得的星数
my_style=LS(’#333366’,base_style=LCS)
基类设置为浅蓝色,传递了实参base_style,使用LightColorizedStyle 类
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)
x_label_rotation=45让标签绕X轴旋转45度
show_legend=False)隐藏图例

效果图如下:
在浏览器中打开python_repos.svg文件
在这里插入图片描述

7、改进Pygal图表

创建Pygal类Config的实例来定制图表的外观。

在python_repos.py文件中修改:

import requests     #导入模块requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))

names,stars=[],[]
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])		#项目名称
    stars.append(repo_dict['stargazers_count'])				#该项目获得的星级

#可视化
my_style=LS('#333366',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=18
my_config.truncate_label=15         #将较长的项目名缩短为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 on GitHub'
chart.x_labels=names

chart.add('',stars)
chart.render_to_file('python_repos.svg')

代码中已详细注释!!!

效果图如下:
在这里插入图片描述

8、添加自定义工具提示

在Pygal中,将鼠标指向条形将显示它表示的信息,这通常成为工具提示。创建一个自定义工具提示已同时显示项目的描述。

新建bar_descriptions.py文件

import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

my_style=LS('#333366',base_style=LCS)
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)

chart.title='Python Projects'
chart.x_labels=['httpie','django','flask']

plot_dicts=[
    {'value':16101,'label':'Description of httpie'},
    {'value':15028,'label':'Description of django'},
    {'value':14798,'label':'Description of flask'}
]

chart.add('',plot_dicts)
chart.render_to_file('bar_descriptions.svg')

plot_dicts=[ ]
定义一个列表,用label相关联字符串给条形创建工具提示
chart.add(’’,plot_dicts)
调用add(),传入传入了一个由表示条形的字典组成的列表
效果图如下:
在这里插入图片描述

9、根据数据绘图

为根据数据绘图,我们将自动生成plot_dicts,其中包含API调用返回的30个项目的信息。

在python_repos.py文件中修改:

import requests     #导入模块requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))

names,plot_dicts=[],[]
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])		#项目名称

    plot_dict={
        'value':repo_dict['stargazers_count'],
        'label':str(repo_dict['description']),
    }
    plot_dicts.append(plot_dict)

#可视化
my_style=LS('#333366',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=18
my_config.truncate_label=15         #将较长的项目名缩短为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 on GitHub'
chart.x_labels=names

chart.add('',plot_dicts)
chart.render_to_file('python_repos.svg')

plot_dict={ }
创建字典,用来存储value(星数)和label(项目描述)
‘value’:repo_dict[‘stargazers_count’],
星数
‘label’:str(repo_dict[‘description’]),
这边要用str来封装不然会报错

效果图如下:
显示了项目描述以及星数
在这里插入图片描述

10、在图表中添加可单击的链接

Pygal允许将图标中的每个条形用作网站的链接。

在python_repos.py文件中修改:

plot_dict={
        'value':repo_dict['stargazers_count'],
        'label':str(repo_dict['description']),
        'xlink':repo_dict['html_url'],
    }

效果如下图所示:
1、将鼠标放在任意条形上,会显现多出了link
在这里插入图片描述
2、点击该条形会跳转到显示该项目的GitHub页面
在这里插入图片描述

综上使用API请求信息,并将信息可视化完毕!!!

附上完整的python_repos.py和bar_descriptions.py文件

python_repos.py

import requests     #导入模块requests
import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

#执行API调用并存储响应
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
r=requests.get(url)         #requests来执行调用
print("Status code",r.status_code)          #输出状态码200表示请求成功

#将API响应存储在一个变量中
response_dict=r.json()      #使用json()将这些信息转换为Python字典
print("Total repositories:",response_dict['total_count'])

#探索有关仓库信息
repo_dicts=response_dict['items']
#print("Repositories returned:",len(repo_dicts))

names,plot_dicts=[],[]
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])		#项目名称

    plot_dict={
        'value':repo_dict['stargazers_count'],
        'label':str(repo_dict['description']),
        'xlink':repo_dict['html_url'],
    }
    plot_dicts.append(plot_dict)

#可视化
my_style=LS('#333366',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=18
my_config.truncate_label=15         #将较长的项目名缩短为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 on GitHub'
chart.x_labels=names

chart.add('',plot_dicts)
chart.render_to_file('python_repos.svg')

bar_descriptions.py

import pygal
from pygal.style import LightColorizedStyle as LCS,LightenStyle as LS

my_style=LS('#333366',base_style=LCS)
chart=pygal.Bar(style=my_style,x_label_rotation=45,show_legend=False)

chart.title='Python Projects'
chart.x_labels=['httpie','django','flask']

plot_dicts=[
    {'value':16101,'label':'Description of httpie'},
    {'value':15028,'label':'Description of django'},
    {'value':14798,'label':'Description of flask'}
]

chart.add('',plot_dicts)
chart.render_to_file('bar_descriptions.svg')

不足之处,请指出,蟹蟹!!!

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值