scrapy 把cookie并转化为字典的形式

时间:2022-07-11 06:44:16

在用scrapy设置cookie的时候,需要从网页上对应的页面把cookie字段复制下来,并转化为字典的形式,下面代码是对cookie的转化过程

# -*- coding: utf-8 -*-

class transCookie(object):
    def __init__(self, cookie):
        self.cookie = cookie

    def stringToDict(self):
        itemDict = {}
        items = self.cookie.split(';')
        for item in items:
            key = item.split('=')[0].replace(' ', '')# 记得去除空格
            value = item.split('=')[1]
            itemDict[key] = value
        return itemDict

cookie = "uuid_tt_dd=-3134286425191133820_20170304;_message_m=tnbfbtmuxpxxyg2050gpiukt;"
trans = transCookie(cookie)
print trans.stringToDict()