When writing crawlers, it is often necessary to process the cookie in the Cookie,requests library as dict, but headers[' cookie ' is a key=value string.
Here are a few of the derivation of the implementation of the conversion function for your reference.
#Coding=utf-8#Create By:joshua Zou#Create date:2018.5ImportLogging#key=value list into cookie dictionarydefcookie_list_2_dict (Cookli):if notisinstance (cookli,list): Logging.error ('Error List param ...') return {} return{Item.split ('=') [0]:item.split ('=') [1] forIteminchCookli}#heads[' Cookie ' string into a cookie dictionarydefcookie_str_2_dict (COOKSTR):if notisinstance (COOKSTR,STR): Logging.error ('error str param ...') return{} cookstr= Cookstr.split (';') returncookie_list_2_dict (COOKSTR)#Cookie Dictionary converted to Key=value listdefcookie_dict_2_list (cookdi):if notisinstance (cookdi,dict): Logging.error ('error dict param ...') return[] Cookli= ["%s=%s"% (Key,value) forKey,valueinchCookdi.items ()]returnCookli#Cookie Dictionary converted to heads[' cookie '] stringdefcookie_dict_2_str (cookdi):if notisinstance (cookdi,dict): Logging.error ('error dict param ...') return ""Cookli=cookie_dict_2_list (Cookdi)return ';'. Join (Cookli)if __name__=='__main__': Cookies= {'AST':'1525005900068b4106e25d4','___BZ':'708632|41171989|2b7718|aladin2_freexx','Platform':'H5'} Cookli=cookie_dict_2_list (cookies) cookstr=cookie_dict_2_str (Cookies)Print('Cook list', Cookli)Print('Cook str', cookstr) cookdi1=cookie_str_2_dict (cookstr) Cookdi2=cookie_list_2_dict (Cookli)Print('Cook dict 1', Cookdi1)Print('Cook dict 2', Cookdi2)
Output Result:
Cook list ['ast=1525005900068b4106e25d4','___bz=708632|41171989|2b7718|aladin2_freexx','Platform=h5']cook str AST=1525005900068B4106E25D4;___BZ=708632|41171989|2b7718|aladin2_freexx;platform=H5cook dict1 {'AST':'1525005900068b4106e25d4','___BZ':'708632|41171989|2b7718|aladin2_freexx','Platform':'H5'}cook dict2 {'AST':'1525005900068b4106e25d4','___BZ':'708632|41171989|2b7718|aladin2_freexx','Platform':'H5'}
Above...
Python3 the following tables and dictionary conversions