python爬虫经常会用到requests库,这个库相对与python自带的urlib库来说比较好用,几天主要是记录下requests库怎么使用cookies进行传输

requests库的简单用法

>>> import requests
>>> url = 'https://www.h3blog.com'
>>>
>>> ret = requests.get(url)
>>> print(ret)
<Response [200]>
>>>

requests在headers中使用cookie

代码如下:

>>> import requests
>>>
>>>
>>> url = 'https://www.h3blog.com'
>>>
>>> headers = {'Cookie':'h3blog'}
>>>
>>> ret = requests.get(url,headers = headers)
>>> print(ret)
<Response [200]>
>>>

requests使用cookies参数进行传值

在requests的get或post方法中有一个cookies参数,该参数类型为字典,只需要将要设置的参数包装成字典就可以传参了

>>> import requests
>>>
>>>
>>> url = 'https://www.h3blog.com'
>>>
>>> cookies = {'h3blog':'la la la la la la '}
>>> ret = requests.get(url,cookies = cookies)
>>> print(ret)
<Response [200]>
>>>

使用requests的session进行请求

>>> session = requests.session()
>>>
>>> url = 'https://www.h3blog.com/login'
>>> data = {'name':'zhangsan','password':'123456'}
>>> session.post(url,data)
<Response [200]>
>>>
>>> session.get(url)
<Response [200]>
>>>