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

在用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()

=================================================

b = 'bid=Qzw9cKnyESM; ll="108288"; __yadk_uid=4YChvgeANLBEh4iV00n1tc0HQ8zpmSl1; __utmc=30149280; __utmc=223695111; _vwo_uuid_v2=D8099FF3ECFE384A3F35BFA190C05A5EE|91f795432cda34bbc17ba6265fb33177; ps=y; dbcl2="169126613:FUpqH/CNWB8"; ck=pyZ7; ap=1; push_noty_num=0; push_doumail_num=0; __utmz=30149280.1520490941.8.7.utmcsr=accounts.douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/login; __utmv=30149280.16912; __utmz=223695111.1520492304.6.4.utmcsr=douban.com|utmccn=(referral)|utmcmd=referral|utmcct=/search; ct=y; __utma=30149280.1712477244.1514880643.1520490941.1520496097.9; __utmb=30149280.0.10.1520496097; __utma=223695111.1169484511.1516955420.1520492304.1520496097.7; __utmb=223695111.0.10.1520496097; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1520496097%2C%22https%3A%2F%2Fwww.douban.com%2Fsearch%3Fsource%3Dsuggest%26q%3D%25E5%2589%258D%25E4%25BB%25BB%22%5D; _pk_ses.100001.4cf6=*; _pk_id.100001.4cf6=21a4461bbb469631.1516955420.7.1520496674.1520492685'
cookie ={}
for line in b.split(';'):

key,value = line.split('=',1)
cookie[key] = value
print(cookie)
---------------------

上一篇:【其他】3dmax撤销Ctrl+z不能用的解决办法


下一篇:Python处理json字符串转化为字典