使用 aiohttp 获取 cookie

Get cookie using aiohttp

我正在尝试使用 aiohttp 从浏览器获取 cookie。从文档和谷歌搜索中,我只找到了有关在 aiohttp 中设置 cookie 的文章。

在烧瓶中,我会像

一样简单地得到饼干
cookie = request.cookies.get('name_of_cookie')
# do something with cookie

是否有使用 aiohttp 从浏览器获取 cookie 的简单方法?

Is there a simple way to fetch the cookie from the browser using aiohttp?

不确定这是否简单但是有办法:

import asyncio
import aiohttp


async def main():
    urls = [
        'http://httpbin.org/cookies/set?test=ok',
    ]
    for url in urls:
        async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as s:
            async with s.get(url) as r:
                print('JSON', await r.json())
                cookies = s.cookie_jar.filter_cookies('http://httpbin.org')
                for key, cookie in cookies.items():
                    print('Key: "%s", Value: "%s"' % (cookie.key, cookie.value))

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

程序生成以下输出:

JSON: {'cookies': {'test': 'ok'}}
Key: "test", Value: "ok"

例子改编自https://aiohttp.readthedocs.io/en/stable/client_advanced.html#custom-cookies + https://docs.aiohttp.org/en/stable/client_advanced.html#cookie-jar

现在,如果您想使用之前设置的 cookie 发出请求:

import asyncio
import aiohttp
url = 'http://example.com'

# Filtering for the cookie, saving it into a varibale
async with aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar()) as s:
cookies = s.cookie_jar.filter_cookies('http://example.com')
for key, cookie in cookies.items():
    if key == 'test':
        cookie_value = cookie.value

# Using the cookie value to do anything you want:
# e.g. sending a weird request containing the cookie in the header instead.
headers = {"Authorization": "Basic f'{cookie_value}'"}
async with s.get(url, headers=headers) as r:
    print(await r.json())


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

根据 https://github.com/aio-libs/aiohttp/issues/1183#issuecomment-247788489

,要测试包含由 IP 地址组成的主机部分的 url,请使用 aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True))

是的,cookie 作为字典存储在 request.cookies 中,就像在 flask 中一样,所以 request.cookies.get('name_of_cookie') 的工作原理相同。

在显示如何检索、设置和删除 cookie 的 examples section of the aiohttp repository there is a file, web_cookies.py 中。这是该脚本中读取 cookie 并将其作为预格式化字符串 returns 发送到模板的部分:

from pprint import pformat
from aiohttp import web

tmpl = '''\
<html>
    <body>
        <a href="/login">Login</a><br/>
        <a href="/logout">Logout</a><br/>
        <pre>{}</pre>
    </body>
</html>'''

async def root(request):
    resp = web.Response(content_type='text/html')
    resp.text = tmpl.format(pformat(request.cookies))
    return resp

您可以获取 cookie 值、域、路径等,而无需遍历所有 cookie。

s.cookie_jar._cookies

为您提供 defaultdict 中的所有 cookie,其中域作为键,它们各自的 cookie 作为值。 aiohttp 使用 SimpleCookie

所以,获取cookie的值

s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"].value

对于域,路径:​​

s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"]["domain"]

s.cookie_jar._cookies.get("https://httpbin.org")["cookie_name"]["path"]

可以在此处找到更多信息:https://docs.python.org/3/library/http.cookies.html