我正在尝试使用aiohttp从浏览器中获取cookie。从文档和googling中,我只找到了关于在aiohttp中设置cookie的文章。
在烧瓶里,我会得到饼干,就像
cookie = request.cookies.get('name_of_cookie')
# do something with cookie是否有一种使用aiohttp从浏览器中获取cookie的简单方法?
发布于 2018-07-27 08:36:34
是否有一种使用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"从Advanced.html#定制-cookie + 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地址组成的主机部件的urls,请使用aiohttp.ClientSession(cookie_jar=aiohttp.CookieJar(unsafe=True)),根据https://github.com/aio-libs/aiohttp/issues/1183#issuecomment-247788489
发布于 2019-01-14 16:02:10
是的,cookies作为一个小块存储在request.cookies中,就像在烧瓶中一样,所以request.cookies.get('name_of_cookie')的工作原理是一样的。
在aiohttp存储库的示例部分中,有一个文件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发布于 2021-12-25 05:06:07
您可以获得cookie值、域、路径等,而不必通过所有cookie循环。
s.cookie_jar._cookies给出默认情况下的所有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
https://stackoverflow.com/questions/51533794
复制相似问题