我正在尝试使用 aiohttp/python 访问一些网站。目前我可以在 Google Chrome 中使用扩展程序导出网站的 cookie,格式如下
.domain.name TRUE / FALSE 1547016401 cookies 值
我可以用
加载它import http.cookiejar
cj = http.cookiejar.MozillaCookieJar('cookies.txt')
cj.load()
cookies = {}
for each in cj:
cookies[each.name] = each.value
并在 aiohttp 中使用
cookies
,例如:
async with ClientSession(cookies=cookies) as session:
有没有更优雅的方法来做到这一点?浏览了 aiohttp 的文档,但没有找到它们。
这是一个将
http.cookiejar.Cookie
对象转换为 list[tuple[str, Morsel]]
对象列表的函数,这些对象可以作为 aiohttp
:传递给
cookies
警告:未经过彻底测试,可能存在错误和/或安全风险。使用风险自负!
from datetime import datetime
from http.cookiejar import Cookie, CookieJar
from http.cookies import Morsel, BaseCookie, CookieError
def morsel(cookie: Cookie) -> Morsel | None:
base_cookie = BaseCookie()
try:
base_cookie[cookie.name] = cookie.value
except CookieError: # Illegal key
return
morsel = base_cookie[cookie.name]
for key in (
'path',
'comment',
'domain',
# 'max-age', Cookie converts 'max-age' to 'expires' internally
'secure',
'version',
):
if (value := getattr(cookie, key, None)) is not None:
morsel[key] = value
if cookie.expires is not None:
morsel['expires'] = datetime.fromtimestamp(
cookie.expires / 1000
).strftime("%a, %d %b %Y %H:%M:%S GMT")
get_nonstandard_attr = getattr(cookie, 'get_nonstandard_attr', None)
if get_nonstandard_attr is not None:
for key in ('HttpOnly', 'SameSite'):
if (value := cookie.get_nonstandard_attr(key, None)) is not None:
morsel[key.lower()] = value
return morsel
def cookie_jar_to_cookies(cj: CookieJar) -> list[tuple[str, Morsel]]:
return [(c.name, m) for c in cj if (m := morsel(c)) is not None]