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_limit 访问,时间是“每分钟”。

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应用。

猜你喜欢

转载自blog.csdn.net/vpointer701/article/details/80030339