直接上代码:
# encoding=utf8
'''
Python2环境下
'''
import requests
def main():
session = requests.session()
# requests.utils.dict_from_cookiejar方法可以将cookiejar对象转换成一个dict对象
cookies = requests.utils.dict_from_cookiejar(session.cookies)
print 'cookies: ', cookies
# 结果:
# cookies: {}
cook1 = {'a': '1', 'b': '2'}
# requests.utils.cookiejar_from_dict方法可以将一个字典转换成cookiejar对象并添加到当前session的cookies中
session.cookies = requests.utils.cookiejar_from_dict(cook1)
cookies = requests.utils.dict_from_cookiejar(session.cookies)
print 'cookies: ', cookies
# 结果:
# cookies: {'a': '1', 'b': '2'}
cook2 = {'c': '3'}
# requests.utils.add_dict_to_cookiejar方法可以为当前的cookies添加新的cookie
requests.utils.add_dict_to_cookiejar(session.cookies, cook2)
cookies = requests.utils.dict_from_cookiejar(session.cookies)
print 'cookies: ', cookies
# 结果:
# cookies: {'a': '1', 'c': '3', 'b': '2'}
verify = session.verify
print 'verify: ', verify
# 结果:
# verify: True
# 取消请求验证,主要针对https请求
session.verify = False
verify = session.verify
print 'verify: ', verify
# 结果:
# verify: False
headers = session.headers
print 'headers: ', headers
# 结果:
# headers: {'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.12.5'}
# 为session添加请求头
session.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0'}
headers = session.headers
print 'headers: ', headers
# 结果:
# headers: {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0'}
if __name__ == '__main__':
main()