1. 在requests里,session对象是一个非常常用的对象,这个对象代表一次用户会话:从客户端浏览器连接服务器开始,到客户端浏览器与服务器断开。
会话能让我们在跨请求的时候保持某些参数,比如在同一个session实例发出的所有请求之间保持cookie信息。
import requests
session = requests.session()
得到session对象之后,就可以调用该对象中方法来发送请求了。
output1 = session.get(url,params,headers)
output2 = session.post(url,data,json,headers)
2. 同时, 我们也可以直接调用requests 发送请求, 但是每次请求都必须包含cookies信息
import requests
output1 = requests.get(url,params,headers,cookies) # 发送get网络请求
output2 = requests.post(url,data,json,headers,cookies) # 发送
区别:
通过代码的对比可发现使用session对象效率会更好,不用每次都将cookie信息放到请求内容中了
session对象能够自动获取到cookie并且可以在下一次请求红自动带上我们所得到的的cookie信息,不用人为的去填写
补充知识点:
可以从请求方法的返回值response中可以获取的内容:
response.status_code 状态码
response.url 请求url
response.encoding 查看响应头部字符编码
response.cookies cookie信息
response.headers 头信息 (包含Auth)
response.text 文本形式的响应内容
response.content 二进制字节形式的响应内容
response.json() JSON形式的响应内容(其实就是dict字典类型) #转换output为json模式,可以字典调用
requests.get() - GET method is used to retrieve information from the given server using a given URI. i.e.获得head+body
requests.put() - the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified and if the URI does not point to an existing resource, then the server can create the resource with that URI, i.e.更新文件
requests.post() - requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it, i.e.上传文件
requests.delete() - The DELETE method deletes the specified resource
requests.head() - The HEAD method asks for a response identical to that of a GET request, but without the response body. 简化版get()
requests.patch() - It is used for modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource,
status_code
Ture:(1xx, 2xx, 3xx)
False:(4xx, 5xx)
URL="http://abc.com/get?page=2&count=20"
URL_NEW="http://abc.com"
payload=dict(page="2",count="20")
res = requests.get(URL, params=payload)
print (res)
https://scotch.io/tutorials/getting-started-with-python-requests-get-requests#toc-headers
key=API_KEY