第 17 章 使用API

输入GitHub的API :    https://api.github.com/search/repositories?q=language:python&sort=stars

17.1 找出github上星级最高的python项目

import requests

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

print(response_dict.keys())


17.1.1

import requests

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}")

#将API响应赋给一个变量

response_dict = r.json()

print(response_dict.keys())

print(f"Total repositories:{response_dict['total_count']}")

#探索有关仓库的信息

repo_dicts = response_dict['items']

print(f"Repositories returned:{len(repo_dicts)}")

#研究第一个仓库

repo_dict = repo_dicts[0]

print({len(repo_dict)})

for key  in sorted(repo_dict.keys()):

     print(key)


17.2 使用 Plotly可视化仓库

import requests

from plotly.graph_objsimport Bar

from plotlyimport offline

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

repo_dicts = response_dict['items']

print(repo_dicts)

repo_names, stars = [], []

for repo_dictin repo_dicts:

          repo_names.append(repo_dict['name'])

          stars.append(repo_dict)

# 可视化

data = [{

'type':'bar',

    'x': repo_names,

    'y': stars

}]

my_layout = {

'title':'Github上最受欢迎的python项目',

    'xaxis': {'title':'Repository'},

    'yaxis': {'title':'Stars'},

}

fig = {'data': data, 'layout': my_layout}

offline.plot(fig, filename='python_repos.html')

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。