正文开始
1.使用API调用请求数据。
进入 https://api.github.com/search/repositories?q=language:python&sort=stars
https://api.github.com/ #将请求发送到Github网站中调用API的部分
search/repositories #让API搜索Github上的仓库
?q= #查询
language:python #语言为Python
sort=stars #排序方式为按star
2.安装 requests
3处理API响应
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(response_dict.keys())
4.处理得到的字典
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 respositories:",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)
我们通过打印字典中的key获取字典包含的东西
...
然后获取我们感兴趣的一些信息
#研究第一个仓库 repo_dict = repo_dicts[0] print("\n关于第一个仓库的一些信息:") print("Name:",repo_dict['name']) print("Owner:",repo_dict['owner']['login']) print("Stars:",repo_dict['stargazers_count']) print("repository:",repo_dict['html_url']) print('Created:',repo_dict['created_at']) print('Updated:', repo_dict['updated_at']) print('Description:',repo_dict['description'])
5.使用遍历批量处理
print("\n关于仓库的一些信息:") for repo_dict in repo_dicts: print("Name:",repo_dict['name']) print("Owner:",repo_dict['owner']['login']) print("Stars:",repo_dict['stargazers_count']) print("repository:",repo_dict['html_url']) print('Created:',repo_dict['created_at']) print('Updated:', repo_dict['updated_at']) print('Description:',repo_dict['description']) print("\n")