gpt4 book ai didi

python-3.x - 使用 aiohttp 获取 cookie

转载 作者:行者123 更新时间:2023-12-01 23:04:37 28 4
gpt4 key购买 nike

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

在 flask 中,我会像得到 cookies 一样简单

cookie = request.cookies.get('name_of_cookie')
# do something with cookie

有没有一种简单的方法来获取 来自浏览器的 cookie 使用 aiohttp ?

最佳答案

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())

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

关于python-3.x - 使用 aiohttp 获取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51533794/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com