由于自用的浏览器cookie管理插件导入导出时用的是字典形式,而python里面对[{}, {}]
的cookies加载支持不太友好。
所以根据RFC6265和RequestsCookieJar源码,写了一个适用于此形式cookie的转换脚本,便于python载入使用。
代码如下:
'''
@作者: weimo
@创建日期: 2020-04-11 21:45:46
@上次编辑时间: 2020-04-11 22:37:48
@一个人的命运啊,当然要靠自我奋斗,但是...
'''
import json
from pathlib import Path
from http.cookiejar import Cookie
from requests.cookies import RequestsCookieJar
def convert(cookies_path: str = "cookies.json"):
# convert [{}, {}] cookies to RequestsCookieJar format
try:
_cookies = json.loads(Path(cookies_path).read_text(encoding="utf-8"))
except Exception as e:
return
BASECOOKIE = {
"version": 0,
"name": "",
"value": "",
"port": None,
"port_specified": False,
"domain": "",
"domain_specified": False,
"domain_initial_dot": False,
"path": "/",
"path_specified": False,
"secure": False,
"expires": None,
"discard": False,
"comment": None,
"comment_url": None,
"rest": {},
}
cookies = RequestsCookieJar()
for c in _cookies:
BASECOOKIE["name"] = c["name"]
BASECOOKIE["value"] = c["value"]
if c["domain"] != "":
BASECOOKIE["domain"] = c["domain"]
BASECOOKIE["domain_specified"] = True
if c["domain"].split(".").__len__() == 3:
BASECOOKIE["domain_initial_dot"] = True
BASECOOKIE["path"] = c["path"]
BASECOOKIE["secure"] = c["secure"]
BASECOOKIE["expires"] = c.get("expirationDate")
if c["path"] != "":
BASECOOKIE["path"] = c["path"]
BASECOOKIE["path_specified"] = True
if c["httpOnly"]:
BASECOOKIE["rest"].update({"httpOnly":None})
if c["hostOnly"]:
BASECOOKIE["rest"].update({"hostOnly":None})
cookies.set_cookie(Cookie(**BASECOOKIE))
return cookies
if __name__ == "__main__":
convert("cookies.json")