1.使用Web API:Web API是网站的一部分,用于与使用非常具体的URL请求特定信息的程序交互。这种请求称为API调用。将使用GitHub的API来请求有关该网站中Python项目的信息,然后使用Pygal生成交互式可视化,以呈现项目的受欢迎程度。Github上的项目存储在仓库中,仓库里包含于项目相关联的一切:代码、项目参与者的信息、问题或bug报告等。GitGub用户可以给项目加星(star)表示支持,或跟踪用户可能想使用的项目。
浏览器访问:https://api.github.com/search/repositories?q=language:python&sort=stars,调用返回GitGub当前托管多少个Python项目,以及有关最受欢迎的Python仓库信息。
使用Python程序向网站请求信息以及检查返回的响应需要安装requests。命令行窗口执行命令:pip install requests。
# -*- coding: GBK -*-
import requests #封装了许多常用方法,若导入不成功,命令窗口执行命令pip install requests
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url) #得到一个响应对象,存储在r中
print("Status code:", r.status_code) #响应对象包含status_code属性(状态码200表示请求成功)
# 将API响应对象存储在一个变量中
response_dict = r.json() #API返回的是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:")
for repo_dict in repo_dicts:
print('\nName:', repo_dict['name'])
print('Owner:', repo_dict['owner']['login']) #owner这项信息也是一个字典,返回owner字典中login对应的值
print('Stars:', repo_dict['stargazers_count'])</