Conclusion:
The request and response of the 1.requests module has a cookie object, respectively. You can set and get cookies from this object.
2. Pass the cookie dictionary parameter in the Requests.get,requests.post and other method request only for a single request cookies setting.
3. Request.session () Returns the object that holds the session. Provides cookie persistence, connection-pooling, and configuration.
1. Request for cookie settings and access
Method One: When the parameter is passed in, the cookie parameter is added at the time of the request, which is only a single request.
Import requests as Requestsmodule
Cookiesdit = {
' Phpsessid ': ' D38k25b2nt90ahhaanuuqghrh6 '
}
Requests = Requestsmodule.session ()
Print (Requests.cookies.get_dict ()) #先打印一下, this should generally be empty.
PostData ={
}
# cookies are set
Rs=requests.post (' http://www.baidu.com ', data = Postdata,headers=headers,cookies=cookiesdit,verify=false)
rs.encoding= ' Utf-8 '
Print (Requests.cookies.get_dict ()) # Cached Cookie
Print (Rs.cookies.get_dict ()) # Gets the cookie for the response setting
Mode two: Set requests Cookie member object
Import requests as Requestsmodule
Cookiesdit = {
' Phpsessid ': ' D38k25b2nt90ahhaanuuqghrh6 '
}
Requests = Requestsmodule.session ()
RequestsModule.utils.add_dict_to_cookiejar (Requests.cookies, Cookiesdit) # The value of this requested cookie object will always be used
Print (Requests.cookies.get_dict ()) #先打印一下, set the cookie to see.
PostData ={
}
# cookies are set
Rs=requests.post (' http://www.baidu.com ', data = Postdata,headers=headers,verify=false)
rs.encoding= ' Utf-8 '
Print (Requests.cookies.get_dict ())
Print (Rs.cookies.get_dict ())
# Use Object mode to set the same effect as RequestsModule.utils.add_dict_to_cookiejar settings
C=requests.cookies.requestscookiejar () #利用RequestsCookieJar获取
C.set (' Cookie-name ', ' Cookie-value ')
S.cookies.update (c)
Refer to the official manual for detailed use
Http://cn.python-requests.org/zh_CN/latest/api.html#requests.PreparedRequest.prepare
Cookie manipulation of Python requests