Search code examples
pythoncookiesmechanize

Python Mechanize set cookie


This below code works.

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)

However, due to some reason, I have to to store c0 as a string. So actually, c0 is a unicode string

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)"

so that

cookiejar.set_cookie(c0) 

return error

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

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

How do I fix this problem? How do I convert unicode string c0 to "something" that cookiejar.set_cookie(c0) can accept?


Solution

  • You can use the exec statement to execute the string stored in c0

    exec "c0 = " + c0
    

    For example:

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

    See: How do I execute a string containing Python code in Python?