我在官方网站上找不到任何关于cookie修改的文件,即没有requests.cookies.RequestsCookieJar
的api文件。
例如,
session = requests.Session()
a = session.head('http://www.google.co.uk')
session.cookies
的百分比抑制率曲奇(版本= 0, 名称= NID', 值= '67 = CXdvwjj9sjd-13Y0VyRQyUs8PxXaxyMhiGrrozXP7RWSjf-5alV4D17ORcfnZNYLAmlHXSVlHuS5LcuE4-v6vnzRQS-Gt72hgbGye0apoBoW5KJeVXA2o2E0gE-8jIeY”, port = None,port_specified = False,domain ='。google.co.uk', domain_specified = True,domain_initial_dot = True,path ='/', path_specified = True,secure = False,expires = 1424443599,discard = False, comment = None,comment_url = None,rest = {'HttpOnly':None}, rfc2109 = False),Cookie(版本= 0,名称='PREF', 值= 'ID = 41c5d5cac7d22262:FF = 0:TM = 1408632399:LM = 1408632399:S = wTfY_LkkZnSsBxoL', port = None,port_specified = False,domain ='。google.co.uk', domain_specified = True,domain_initial_dot = True,path ='/', path_specified = True,secure = False,expires = 1471704399,discard = False, comment = None,comment_url = None,rest = {},rfc2109 = False)]>
现在我要更改'NID'的值
如果我执行session.cookies['NID'] = 'abc'
,最终会出现重复的密钥,如下所示:
的百分比抑制率曲奇(版本= 0, name ='NID',value ='abc',port = None,port_specified = False,domain ='', domain_specified = False,domain_initial_dot = False,path ='/', path_specified = True,secure = False,expires = None,discard = True, comment = None,comment_url = None,rest = {'HttpOnly':None}, rfc2109 = False),Cookie(版本= 0,名称='NID', 值= '67 = CXdvwjj9sjd-13Y0VyRQyUs8PxXaxyMhiGrrozXP7RWSjf-5alV4D17ORcfnZNYLAmlHXSVlHuS5LcuE4-v6vnzRQS-Gt72hgbGye0apoBoW5KJeVXA2o2E0gE-8jIeY”, port = None,port_specified = False,domain ='。google.co.uk', domain_specified = True,domain_initial_dot = True,path ='/', path_specified = True,secure = False,expires = 1424443599,discard = False, comment = None,comment_url = None,rest = {'HttpOnly':None}, rfc2109 = False),Cookie(版本= 0,名称='PREF', 值= 'ID = 41c5d5cac7d22262:FF = 0:TM = 1408632399:LM = 1408632399:S = wTfY_LkkZnSsBxoL', port = None,port_specified = False,domain ='。google.co.uk', domain_specified = True,domain_initial_dot = True,path ='/', path_specified = True,secure = False,expires = 1471704399,discard = False, comment = None,comment_url = None,rest = {},rfc2109 = False)]>
我目前的方法是首先执行session.cookies['NID'] = None
,这会删除键/值,然后session.cookies['NID'] = 'abc'
这有时会有效,但它会完全忽略Cookie属性。
这样做的正确方法是什么?
答案 0 :(得分:3)
正如您所看到的,您的Cookie没有为其指定域名,因此它实际上是另一个Cookie。
使用域名和路径
session.cookies.set('NID', 'abc', domain='.google.co.uk', path='/')
将设置新的cookie而不是之前定义的cookie。
RequestCookieJar
是cookielib.CookieJar
的包装器,但是如果你想要就地修改cookie属性(以便引用实际的cookielib.Cookie
对象),我发现没有比使用迭代器。
如果您查看requests.cookies.RequestsCookieJar
的来源,则没有其他方法可以让您自己访问项目,而不是name
/ value
字段。