Python - convert set-cookies response to dict of cookies

亡梦爱人 提交于 2019-12-07 13:21:46

问题


How to convert the response['set-cookie'] output string from httplib2 response like

"cookie1=xxxyyyzzz;Path=/;Expires=Wed, 03-Feb-2015 08:03:12 GMT;Secure;HttpOnly, cookie2=abcdef;Path=/;Secure"

to

{'cookie1':'xxxyyyzzz','cookies2':'abcdef'}

回答1:


Use http.cookies:

>>> c = "cookie1=xxxyyyzzz;Path=/;Expires=Wed, 03-Feb-2015 08:03:12 GMT;Secure;HttpOnly, cookie2=abcdef;Path=/;Secure"
>>> from http.cookies import SimpleCookie
>>> cookie = SimpleCookie()
>>> cookie.load(c)
>>> cookie
<SimpleCookie: cookie1='xxxyyyzzz' cookie2='abcdef'>
>>> {key: value.value  for key, value in cookie.items()}
{'cookie1': 'xxxyyyzzz', 'cookie2': 'abcdef'}



回答2:


def parse_dict_cookies(value):
    result = {}
    for item in value.split(';'):
        item = item.strip()
        if not item:
            continue
        if '=' not in item:
            result[item] = None
            continue
        name, value = item.split('=', 1)
        result[name] = value
    return result


来源:https://stackoverflow.com/questions/21522586/python-convert-set-cookies-response-to-dict-of-cookies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!