使用aiohttp获取cookie

7
我会尽力为您翻译中文。这篇文章讨论了使用aiohttp从浏览器获取cookies的方法。在查阅文档和搜索后,我只发现有关如何在aiohttp中设置cookies的文章。
在Flask中,获取cookies可以很简单地实现。
cookie = request.cookies.get('name_of_cookie')
# do something with cookie

有没有一种简单的方法使用aiohttp从浏览器中获取cookie?
3个回答

9

有没有一种简单的方法使用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())

该程序生成以下输出:
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())

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


4

是的,cookie以字典形式存储在request.cookies中,就像在flask中一样,因此request.cookies.get('name_of_cookie')的使用方式也相同。

在aiohttp存储库的examples部分中,有一个文件web_cookies.py,展示了如何检索、设置和删除cookie。以下是该脚本中读取cookie并将其作为预格式化字符串返回到模板的部分:

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

1
你可以获取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


(注意:本文不包含解释,保留HTML标签)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接