Cookies 使用Asyncio支持会话cookie

Cookies 使用Asyncio支持会话cookie,cookies,python-3.x,python-asyncio,redirectwithcookies,aiohttp,Cookies,Python 3.x,Python Asyncio,Redirectwithcookies,Aiohttp,我用python编写了一个废弃脚本,需要与Asyncio一起使用。我还需要它来支持网络cookies。最初使用urllib.request创建的脚本如下所示: urls = ['example.com/subdomain-A', 'example.com/subdomain-B', 'example.com/subdomain-C', ...] for url in urls: page = bs4.BeautifulSoup(urllib.request.build_opener(re

我用python编写了一个废弃脚本,需要与Asyncio一起使用。我还需要它来支持网络cookies。最初使用urllib.request创建的脚本如下所示:

urls = ['example.com/subdomain-A', 'example.com/subdomain-B', 'example.com/subdomain-C', ...]
for url in urls:
    page = bs4.BeautifulSoup(urllib.request.build_opener(req.HTTPCookieProcessor).open(url))
    # Do some stuff with page
目前这很好,但我还需要使用Asyncio使其成为多线程。由于我没有找到任何关于它的文档,我尝试了以下方法:

@asyncio.coroutine
def get(*args, **kwargs):
    response = yield from aiohttp.request('GET', *args, **kwargs)
    res = yield from response.read()
    return res

@asyncio.coroutine
def scraper(url):
    connector = aiohttp.connector.BaseConnector(share_cookies=True)
    response = yield from get(url, connector=connector)
    page = bs4.BeautifulSoup(response)
    # Do some stuff with page

urls = ['example.com/subdomain-A', 'example.com/subdomain-B', 'example.com/subdomain-C', ...]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = [scraper(url) for url in urls]
loop.run_until_complete(asyncio.wait(tasks))
就上下文而言,我试图抓取的页面是以这样一种方式制作的:它们在加载时测试会话cookie是否存在,如果不存在,则创建一个,然后重定向到它们自己。现在,使用一种简单的抓取方法,我陷入了一个循环,而使用Asyncio/Aiohttp,什么都不会发生


谢谢您的帮助。

首先,您应该使用
TCPConnector
,而不是
BaseConnector
。接下来,使用
asyncio.async
asyncio.Task
运行并行任务。我的意思是
asyncio.async(scraser(url))
我的方法基于这样一个事实,即大约有30多个进程同时发出网络请求。事实上,只有实际的网络I/O需要是异步的。这就是为什么我改用asyncio.wait。但是谢谢你的评论。