Python Mechanize设置cookie

时间:2018-05-19 05:12:31

标签: python cookies mechanize

以下代码有效。

cookiejar =cookielib.LWPCookieJar()
br.set_cookiejar(cookiejar)

c0 = cookielib.Cookie(version=0, name='_mobile_sess', value='BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoQX2NzcmZfdG9rZW4iLTY4YWYxODc5ZmVlNTRhMDM4YzUwN2VjMmNiMWJkMjZlMTIxNDViNWM%3D--a18dca22d18735ebb9c4f91f595bae999e138f5e', port=None, port_specified=False, domain='.twitter.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=True, expires=1531884528, discard=False, comment=None, comment_url=None, rest={'HTTPOnly': None}, rfc2109=False)

cookiejar.set_cookie(c0)

但是,由于某种原因,我必须将c0存储为字符串。 实际上,c0是一个unicode字符串

c0 = u"cookielib.Cookie(version=0, name='_mobile_sess', value='BAh7ByIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoQX2NzcmZfdG9rZW4iLTY4YWYxODc5ZmVlNTRhMDM4YzUwN2VjMmNiMWJkMjZlMTIxNDViNWM%3D--a18dca22d18735ebb9c4f91f595bae999e138f5e', port=None, port_specified=False, domain='.twitter.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=True, expires=1531884528, discard=False, comment=None, comment_url=None, rest={'HTTPOnly': None}, rfc2109=False)"

这样

cookiejar.set_cookie(c0) 

返回错误

if cookie.domain not in c: c[cookie.domain] = {}

AttributeError: 'Text' object has no attribute 'domain'

如何解决此问题?如何将unicode字符串c0转换为"" cookiejar.set_cookie(c0)可以接受吗?

1 个答案:

答案 0 :(得分:1)

您可以使用exec语句执行c0

中存储的字符串
exec "c0 = " + c0

例如:

>>> exec u"print('hello')"
hello

请参阅:How do I execute a string containing Python code in Python?