python + requests-- advanced usage - the focus of treatment cookie--

Reference website: https://www.cnblogs.com/xiaobaibailongma/p/12346091.html

import  requests

url = 'http://www.baidu.com'

resp = requests.get(url)

print(resp.cookies)

print('============================================================')

for k,v in resp.cookies.items():
    print(k,'=',v)

Results of the:

 

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
============================================================
BDORZ = 27315

 

===================================================================================================================

 

Use python's requests to develop crawlers, it often needs to be requested before the cookie value returned as the next request cookie call,

 

For example sessionID returned after login analog, as is the need for a subsequent request parameter cookie

Divided into three steps:

  1, introduced by requests from requests.cookies import RequestsCookieJar module

  2, is instantiated: jar = RequestsCookieJar ()

  3, set: jar.set (cookie [ 'name'], cookie [ 'value'])

  

After the completion of the request will be sent directly together at the time of the request web page source file, this cookie will bring

 

import  requests
from requests.cookies import RequestsCookieJar

url = 'http://www.baidu.com'

resp = requests.get(url)

print(resp.cookies)

print('============================================================')

for k,v in resp.cookies.items():
    print(k,'=',v)

print('============================================================')

jar = RequestsCookieJar()

jar.set('BDORZ', '27315')

r = requests.get(url,cookies=jar)

print(r.status_code)

 

Results of the:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
============================================================
BDORZ = 27315
============================================================
200

 

 

===========================================================================================

 

 

Guess you like

Origin www.cnblogs.com/xiaobaibailongma/p/12355292.html