cookies转换

class transCookie: def __init__(self, cookie): self.cookie = cookiedef stringToDict(self): ''' 将从浏览器上Copy来的cookie字符串转化为Dict :return: ''' itemDict = {} items = self.cookie.split('; ') for item in items: key = item.split('=')[0].replace(' ', '') value = https://www.it610.com/article/item.split('=')[1] itemDict[key] = value return itemDictif __name__ == "__main__": cookie = "你复制出的cookie" trans = transCookie(cookie) print(trans.stringToDict())

以下是另一段代码,简单得多:

# -*- coding: UTF-8 -*- import redef cookie_dict(cookie_str): first = re.sub("(.*?)=(.*?); ",'"\\1":"\\2",\n',cookie_str) print(first) print("===================================") sec = re.sub(",\n([^\"]*?)=(.*)",',\n"\\1":"\\2"',first) sec = "cookies={"+sec+"}" print(sec)cookie_str = "JSESSIONID=894C3BA096AC511C0840BB7CD7180D48; __utma=18602731.1225917530.1600359625.1600359625.1600359625.1; __utmc=18602731; __utmz=18602731.1600359625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __utmb=18602731.1.10.1600359625" cookie_dict(cookie_str)


测试一下:
# -*- coding: UTF-8 -*- import redef cookie_dict(cookie_str): print(cookie_str) print("=================first===================") first = re.sub("(.*?)=(.*?); ",'"\\1":"\\2",\n',cookie_str) print(first) print("=================test====================") test = re.sub("(.*)=(.*?); ", '"\\1":"\\2",\n', cookie_str) print(test) print("===================second================") sec = re.sub(",\n([^\"]*?)=(.*)",',\n"\\1":"\\2"',first) print(sec) print("=================third===================") third = "cookies={"+sec+"}" print(third)# cookie_str = "JSESSIONID=894C3BA096AC511C0840BB7CD7180D48; __utma=18602731.1225917530.1600359625.1600359625.1600359625.1; __utmc=18602731; __utmz=18602731.1600359625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __utmb=18602731.1.10.1600359625" cookie_str = "__utmz=18602731.1600359625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=18602731.1.10.1600359625" cookie_dict(cookie_str)

【cookies转换】从结果来看,对于“__utmz=18602731.1600359625.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)”这类有多个“=”的,是将第一个“=”转变成字典里面的“:”

    推荐阅读