Python 使用requests模块 执行Web API调用 获取网站数据并可视化

import requests

#执行web api调用,并将响应存储在response_dict字典中
url='https://api.github.com/search/repositories?q=language:python&sort=stars'
headers={'Accept':'application/vnd.github.v3+json'}
r=requests.get(url,headers=headers)
print(f'Status code:{r.status_code}')
response_dict = r.json()

使用网站提供的API可以使用requests.get方法获得网站数据。

网站数据保存在变量r中。

当r.status_code为200是,表明获得的数据是完整的。

再使用r.json()方法,将获得的数据保存在‘字典’response_dict中。

对字典中的数据结构进行整理,筛选,可以进一步实现数据可视化。

数据处理过程如下:

repo_dicts = response_dict['items']
repo_names = [repo_dict['name'] for repo_dict in repo_dicts]
stars = [repo_dict['stargazers_count'] for repo_dict in repo_dicts]
labels = [f"{repo_dict['owner']['login']}<br />{repo_dict['description']}" for repo_dict in repo_dicts]
repo_links = [f"<a href='{repo_dict['html_url']}'>{repo_dict['name']}</a>" for repo_dict in repo_dicts]

可视化设置如下:

from plotly.graph_objs import Bar
from plotly import offline

data = [{
    'type':'bar',#绘制柱状图
    'x':repo_links,#x轴名称为链接,可与用户交互
    'y':stars,
    'hovertext':labels,#鼠标悬停显示label信息
    'marker':{
        'color':'rgb(60,100,150)',
        'line':{'width':1.5,'color':'rgb(2,5,25,25)'}
    },#修改柱状图默认颜色
    'opacity':0.6,#修改色彩透明度
}]

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')

最终运行结果:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值