import request #导入模块
#执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' #存储API调用的url
headers = {'Accpet':'application/vnd/github.v3+json'} #API版本
r = requests.get(url,headers = headers) #request调用API,get()响应对象赋给r
print(f"Status code:{r.status_code}") #status_code指出请求是否成功,状态码200表示请求成功
#将API响应赋给一个变量
response_dict = r.json() #json转换为字典
#打印与'total_count'相关联值,指出总共包含多少Python仓库
print(f"Total repositories:{response_dict['total_count']}")
#探索有关仓库的信息
repo_dicts = response_dict['items'] #items关联值是列表,其中包含很多字典
print(f"Repositories returned:{len(repo_dicts)}") #打印长度
#研究第一个仓库
repo_dict = respo_dicts[0]
print(f"\nkeys:{len(repo_dict)}") #输出长度
for key in sorted(repo_dict.keys()): 打印所有键
print(key)
#遍历所有字典
for repo_dict in repo_dicts:
#提取键相关联的值
print(f"Name:{repo_dict['name']}") #项目名称
'''
owner login #所有者-登录名
stargazers_count #星 评级
html_url #GitHub仓库URL
created_at #创造时间
updated_at #更新时间
describe #仓库描述
'''
#处理结果
print(response_dict.keys())
监视API速率限制:
https://api.github.com/rate_limit
{
"resources":{
"core":{
"limit":60,
"remaining":60,
"reset":1614491948,
"used":0
},
"graphql":{
"limit":0,
"remaining":0,
"reset":1614491948,
"used":0
},
"integration_manifest":{
"limit":5000,
"remaining":5000,
"reset":1614491948,
"used":0
},
"search":{ #探索API速率限制
"limit":10, #极限为每分钟10个请求
"remaining":10, #在当前分钟内,还可执行8个请求
"reset":1614488408, #配额将重置的Unix时间或新纪元时间(1970年1月1日午夜后多少秒)
"used":0
}
},
"rate":{
"limit":60,
"remaining":60,
"reset":1614491948,
"used":0
}
}
使用plotly可视化仓库:
import request #导入模块
from plotly.graph_objs import Bar
from plotly import offline
#执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' #存储API调用的url
headers = {'Accpet':'application/vnd/github.v3+json'} #API版本
r = requests.get(url,headers = headers) #request调用API,get()响应对象赋给r
print(f"Status code:{r.status_code}") #status_code指出请求是否成功,状态码200表示请求成功
#处理结果
response_dict = r.json() #json转换为字典
#探索有关仓库的信息
repo_dicts = response_dict['items'] #items关联值是列表,其中包含很多字典
repo_names,stars = [],[] #创建两个空列表存储数据
#遍历所有字典
for repo_dict in repo_dicts:
repo_names.append(repo_dict['name'])
stars.append(repo_dict['stargazers_count'])
#可视化
data = [{
'type':'bar', #图标类型
'x':repo_names, #x值
'y':stars, #y值
'maker':{
'color':'rgb(60,100,150)', #蓝色
'line':{'width':1.5,'color':'rgb(25,25,25)'} #宽1.5像素的深灰色轮廓
},
'opacity':0.6, #不透明度0.6
}]
my_layout = {
'title':'Github上最受欢迎的Python项目', #图标名称
'titlefont':{'size':28},
#x轴标签
'xaxis':{
'title':'Repository',
'titlefont':{'size':24},
'tickfont':{'size':14}, #刻度表字号
},
#y轴标签
'yaxis':{
'title':'Stars',
'titlefont':{'size':24},
'tickfont':{'size':14}, #刻度表字号
},
}
fig = {'data':data,'layout':my_layout}
offline.plot(fig,filename='python_repos.html')