当前位置: 首页 > news >正文

Python学习之路16-使用API

《Python编程:从入门到实践》笔记。
本篇是Python数据处理的第三篇,本篇将使用Web应用程序接口自动请求网站的特定信息并可视化。

1. 前言

本将需要用到requests模块来请求网站数据。主要内容如下:

  • 向GitHub请求项目数据,按星排序;
  • 使用pygal可视化上述数据;
  • 调用Hacker News的API

2. GitHub repositories

获取GitHub中仓库的描述信息,并按星数排序:

# 代码:
import requests

# 执行API调用并存储响应,注意不要输错了!
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url)
print("Status code:", r.status_code)

# 将API响应存储在一个变量中
response_dict = r.json()
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)
    
# 结果:
Status code: 200
Total repositories: 2563652
Repositories returned: 30

Keys: 72
archive_url
archived
assignees_url
blobs_url
-- snip --

有些请求可能并不能成功,可能需要你的个人授权码:

headers = {"Authorization":"your perosonal token"}
url = "https://api.github.com/search/repositories?q=language:python&sort=stars"
r = requests.get(url, headers=headers)

大多数API都存在速率限制,即特定时间内可执行的请求数。对于GitHub的速率限制可以访问 https://api.github.com/rate_l... 访问,时间是“每分钟”。

3. 使用Pygal可视化仓库

使用一个参数配置类来定义图表的参数,并自定义图表中每个条形的描述信息,并给这些条形添加网址链接。

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

-- snip --
repo_dicts = response_dict["items"]

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict["name"])

    plot_dict = {
        # 每个数据的值
        "value": repo_dict["stargazers_count"],
        # 自定义每个数据的描述信息
        # 原文中没有将其转换成str,报错;可能现在数据类型更改了?
        "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()
# x轴标签顺时针旋转45度
my_config.x_label_rotation = 45
# 不显示图例
my_config.show_legend = False
my_config.title_font_size = 24
my_config.label_font_size = 14
# 主标签大小,y轴
my_config.major_label_font_size = 18
# x轴标签最长15个字符
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 on GitHub"
chart.x_labels = names

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

得到如下表格:

图片描述

现在每一个数据都有自己的描述信息,并且点击它们还能跳到它们的项目网站。注意左侧y轴上的刻度,书中的刻度很密集,但同样的代码在这里不知道为什么很稀疏,所以这里没有体现出第34行代码的效果。

4. Hacker News API

Hacker News的API能让你访问该网站所有文章和评论的信息,且不用注册获取秘钥。下面通过一个API调用获取其上当前热门文章的ID,再查看前30篇文章(有可能访问不了,至于原因以及具体怎么做,你懂的):

import requests
from operator import itemgetter

# 执行API调用并存储响应
url = "https://hacker-news.firebaseio.com/v0/topstories.json"
r = requests.get(url)
print("Status code:", r.status_code)

# 处理有关每篇文章的信息
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
    # 对于每篇文章,都执行一个API调用
    url = ("https://hacker-news.firebaseio.com/v0/item/" + str(submission_id) + ".json")
    submission_r = requests.get(url)
    print(submission_r.status_code)
    response_dict = submission_r.json()

    submission_dict = {
        "title": response_dict["title"],
        "link": "http://news.ycombinator.com/item?id=" + str(submission_id),
        "comments": response_dict.get("descendants", 0)
    }
    submission_dicts.append(submission_dict)

submission_dicts = sorted(submission_dicts, key=itemgetter("comments"), reverse=True)

for submission_dict in submission_dicts:
    print("\nTitle:", submission_dict["title"])
    print("Discussion link:", submission_dict["link"])
    print("Comments:", submission_dict["comments"])

以下是输出结果:

Status code: 200
200
200
-- snip --

Title: Wells Fargo Hit with $1B in Fines
Discussion link: http://news.ycombinator.com/item?id=16886328
Comments: 358

Title: Want airline food? Take Amtrak
Discussion link: http://news.ycombinator.com/item?id=16882231
Comments: 160

-- snip --

5. 小结

目前已经完成了两个项目,这本书还剩最后一个Django项目,从下一篇开始,也是用三篇文章来初步了解Django,制作一个简单的web应用。


迎大家关注我的微信公众号"代码港" & 个人网站 www.vpointer.net ~

相关文章:

  • 报错:在做往下拉选里面拼接数据的时候 3个下拉选显示一个值 原因 @scope(单例)或者没配默认单例...
  • flask接收请求并推入栈
  • 从PRISM开始学WPF(八)导航Navigation?
  • 手把手教你将单机游戏改造成对战网游(附详细教程)
  • P2264 情书
  • Spring Boot的@Service和@Autowired和@ComponentScan注解
  • 两个变量交换的四种方法(Java)
  • 分布式消息队列ActiveMQ+Spring整合
  • Vue2.x学习三:事件处理生命周期钩子
  • MySQL的prompt不生效的问题
  • Django之ModelForm(二)-----ModelForm组件
  • Lua使用总结
  • Python模块-threading模块
  • xtrabackup 备份原理
  • tkinter简单打开网址 + 执行系统命令
  • 实现windows 窗体的自己画,网上摘抄的,学习了
  • CSS居中完全指南——构建CSS居中决策树
  • Dubbo 整合 Pinpoint 做分布式服务请求跟踪
  • es6要点
  • Java 23种设计模式 之单例模式 7种实现方式
  • miniui datagrid 的客户端分页解决方案 - CS结合
  • ng6--错误信息小结(持续更新)
  • PAT A1017 优先队列
  • Redis提升并发能力 | 从0开始构建SpringCloud微服务(2)
  • SegmentFault 社区上线小程序开发频道,助力小程序开发者生态
  • Selenium实战教程系列(二)---元素定位
  • sublime配置文件
  • Vue实战(四)登录/注册页的实现
  • 关于springcloud Gateway中的限流
  • 力扣(LeetCode)22
  • 七牛云假注销小指南
  • 由插件封装引出的一丢丢思考
  • gunicorn工作原理
  • ​iOS实时查看App运行日志
  • ​Linux·i2c驱动架构​
  • ​学习一下,什么是预包装食品?​
  • #include到底该写在哪
  • #pragam once 和 #ifndef 预编译头
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (02)vite环境变量配置
  • (2)STM32单片机上位机
  • (PWM呼吸灯)合泰开发板HT66F2390-----点灯大师
  • (附源码)spring boot公选课在线选课系统 毕业设计 142011
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (力扣记录)1448. 统计二叉树中好节点的数目
  • (一一四)第九章编程练习
  • (转贴)用VML开发工作流设计器 UCML.NET工作流管理系统
  • .jks文件(JAVA KeyStore)
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • .NET Core 成都线下面基会拉开序幕
  • .Net Core缓存组件(MemoryCache)源码解析
  • .net 生成二级域名
  • @Import注解详解
  • @RequestMapping用法详解
  • [].shift.call( arguments ) 和 [].slice.call( arguments )