使用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 requestsimport 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--")