# 向国际空间站网页服务器发出一个数据请求,并获取请求的状态码
import requests
response = requests.get("http://api.open-notify.org/iss-now.json")
status_code = response.status_code
output:200
状态码分为:
response = requests.get("http://api.open-notify.org/iss-pass.json")
status_code = response.status_code
print(status_code)
output:
400
查询ISS会发现该请求需要两个参数,经纬度,该请求返回的是ISS下一次经过指定经纬度位置的时间。
# Set up the parameters we want to pass to the API.
# This is the latitude and longitude of New York City.
parameters = {"lat": 40.71, "lon": -74}
# Make a get request with the parameters.
response = requests.get("http://api.open-notify.org/iss-pass.json", params=parameters)
# Print the content of the response (the data the server returned)
# This gets the same data as the command above
response = requests.get("http://api.open-notify.org/iss-pass.json?lat=40.71&lon=-74")
#推荐第一种
JSON is a way to encode data structures like lists and dictionaries to strings that ensures that they are easily readable by machines. JSON is the primary format in which data is passed back and forth to APIs.
print response.content
返回的是一个string,从结果中我们很难看出我们想要的东西。然而json这个库可以将字典和列表编码为字符串,使得机器更容易处理。
json库有两个很重要的方法:
# Make a list of fast food chains.
best_food_chains = ["Taco Bell", "Shake Shack", "Chipotle"]
print(type(best_food_chains))
# Import the json library
import json
# Use json.dumps to convert best_food_chains to a string.
best_food_chains_string = json.dumps(best_food_chains)
print(type(best_food_chains_string))
# Convert best_food_chains_string back into a list
print(type(json.loads(best_food_chains_string)))
# Make a dictionary
fast_food_franchise = {
"Subway": 24722,
"McDonalds": 14098,
"Starbucks": 10821,
"Pizza Hut": 7600
}
# We can also dump a dictionary to a string and load it.
fast_food_franchise_string = json.dumps(fast_food_franchise)
print(type(fast_food_franchise_string))
output:
<class 'list'>
<class 'str'>
<class 'list'>
<class 'str'>
注意:将list变为string后,list[1,2,3]—>str[1,2,3],list[0] == 1而str[0]=[
response.json() output:
{'response': [{'duration': 369, 'risetime': 1441456672}, {'duration': 626, 'risetime': 1441462284}, {'duration': 581, 'risetime': 1441468104}, {'duration': 482, 'risetime': 1441474000}, {'duration': 509, 'risetime': 1441479853}], 'message': 'success', 'request': {'datetime': 1441417753 , 'longitude': -122.41, 'passes': 5, 'altitude': 100, 'latitude': 37.78}} , 'longitude': -122.41, 'passes': 5, 'altitude': 100, 'latitude': 37.78}}
get的内容包括三块:
- ‘response’:包括一个list,list中是dict数据,总共5次经过旧金山
- ‘message’:’success’,表示信息get成功
- ‘request’:请求的相关数据
并不是所有的数据都用json编码,上面用response.json()是因为这个网站将所有的list和dict编码为json,因此可以用json解码。
response.headers中存放了一些与信息生成以及编码相关的信息,其中content-type是最重要的一个键,对于一个不知道编码类型的网站,我们可以用下面代码来获取编码信息:
content_type = response.headers["content-type"]