使用aiohttp获取cookie

Tee*_*emu 2 cookies python-3.x aiohttp

我正在尝试使用aiohttp从浏览器获取cookie.从文档和谷歌搜索我只发现有关在aiohttp中设置cookie的文章.

在烧瓶中,我会简单地得到饼干

cookie = request.cookies.get('name_of_cookie')
# do something with cookie
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以使用aiohttp从浏览器中获取cookie

小智 6

有没有一种简单的方法可以使用aiohttp从浏览器中获取cookie?

不确定这是否简单,但有一种方法:

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())
Run Code Online (Sandbox Code Playgroud)

该程序生成以下输出:

JSON: {'cookies': {'test': 'ok'}}
Key: "test", Value: "ok"
Run Code Online (Sandbox Code Playgroud)

示例改编自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())
Run Code Online (Sandbox Code Playgroud)

用于测试包含由IP地址组成的主机部分的URL aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True)),根据https://github.com/aio-libs/aiohttp/issues/1183#issuecomment-247788489