使用API

------摘自百度百科------

API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

------

简单来说API就是一个提供功能的接口。

Web API

Web API是网络应用程序接口。包含了广泛的功能,网络应用通过API接口,可以实现存储服务、消息服务、计算服务等能力,利用这些能力可以进行开发出强大功能的web应用。

------ END------

正文开始

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




猜你喜欢

转载自blog.csdn.net/qq_41068877/article/details/80726075