python Web API 的使用

使用Python Web API 可以动态获取网站上的信息。《Python编程:从入门到实践》袁国忠译 , 第17章讲解了有关这方面的内容。

首先要安装 requests 包:

python -mpip install --user requests

对于Github ,在运行书上的内容之前,需要获得一个 token。使用requests.get 等方法时把 token作为 headers加入实参。 
# Make an API call and store the response.

 在 https://github.com/settings/tokens 获得 token。如图:


这样发request:

token = "......"

headers1 = {"Authorization": token} 

url = 'https://api.github.com/search/users?q=trump'

r = requests.get(url , headers=headers1 )

Github所提供的api在这里: https://api.github.com/


获取 *** 这个用户的 repo 信息可用下面这些代码:

import requests
import json 
print("s--")

token = "***"
headers1 = {"Authorization": token} 

# Make an API call and store the response.
#url = 'https://api.github.com/search/repositories?q=python&sort=stars'
url = 'https://api.github.com/search/users?q=***'
r = requests.get(url , headers=headers1 )
print("Status code:", r.status_code)
# Store API response in a variable.
response_dict = r.json()
with open('fig/user.json' , 'w')  as f :
    json.dump( response_dict , f )

if  response_dict['total_count'] < 1 :
    exit()

users_list = response_dict["items"]
for user in users_list :
    print( user["repos_url"] )
    r = requests.get(  user["repos_url"] , headers=headers1 )
    repo_list = r.json()
    for repo in repo_list :
        print( repo['name']+":" +  repo['full_name'] ) 

print("e--")


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值