Python——Requests

来源:互联网 发布:淘宝卖家衣服轮播图 编辑:程序博客网 时间:2024/06/05 19:25

get——请求网页数据

# 向国际空间站网页服务器发出一个数据请求,并获取请求的状态码import requestsresponse = requests.get("http://api.open-notify.org/iss-now.json")status_code = response.status_codeoutput:200

状态码分为:

  • 200 – everything went okay, and the result has been returned (if
    any)
  • 301 – the server is redirecting you to a different endpoint. This
    can happen when a company switches domain names, or an endpoint name
    is changed.
  • 401 – the server thinks you’re not authenticated. This happens when
    you don’t send the right credentials to access an API (we’ll talk
    about this in a later mission).
  • 400 – the server thinks you made a bad request. This can happen when
    you don’t send along the right data, among other things.
  • 403 – the resource you’re trying to access is forbidden – you don’t
    have the right permissions to see it.
  • 404 – the resource you tried to access wasn’t found on the server.
response = requests.get("http://api.open-notify.org/iss-pass.json")status_code = response.status_codeprint(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 aboveresponse = requests.get("http://api.open-notify.org/iss-pass.json?lat=40.71&lon=-74")#推荐第一种

JSON Format——JavaScript Object Notation

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库有两个很重要的方法:

  • dumps – Takes in a Python object, and converts it to a string. loads
  • Takes a json string, and converts it to a Python object.
# Make a list of fast food chains.best_food_chains = ["Taco Bell", "Shake Shack", "Chipotle"]print(type(best_food_chains))# Import the json libraryimport 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 listprint(type(json.loads(best_food_chains_string)))# Make a dictionaryfast_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’:请求的相关数据


Content type

并不是所有的数据都用json编码,上面用response.json()是因为这个网站将所有的list和dict编码为json,因此可以用json解码。
response.headers中存放了一些与信息生成以及编码相关的信息,其中content-type是最重要的一个键,对于一个不知道编码类型的网站,我们可以用下面代码来获取编码信息:

content_type = response.headers["content-type"]
0 0
原创粉丝点击