diff --git a/requests_html.py b/requests_html.py index 61893ae..b301cd6 100644 --- a/requests_html.py +++ b/requests_html.py @@ -759,3 +759,13 @@ class AsyncHTMLSession(BaseSession): if hasattr(self, "_browser"): await self._browser.close() super().close() + + def run(self, *coros): + """ Pass in all the coroutines you want to run, it will wrap each one + in a task, run it and wait for the result. Retuen a list with all + results, this are returned in the same order coros are passed in. """ + tasks = [ + asyncio.ensure_future(coro()) for coro in coros + ] + done, _ = self.loop.run_until_complete(asyncio.wait(tasks)) + return [t.result() for t in done] diff --git a/tests/test_internet.py b/tests/test_internet.py index 9bdc51a..8cf6fb9 100644 --- a/tests/test_internet.py +++ b/tests/test_internet.py @@ -1,5 +1,5 @@ import pytest -from requests_html import HTMLSession, AsyncHTMLSession +from requests_html import HTMLSession, AsyncHTMLSession, HTMLResponse session = HTMLSession() @@ -30,3 +30,21 @@ async def test_async_pagination(event_loop): for page in pages: r = await asession.get(page) assert await r.html.__anext__() + + +def test_async_run(): + asession = AsyncHTMLSession() + + async def test1(): + return await asession.get('https://xkcd.com/1957/') + + async def test2(): + return await asession.get('https://reddit.com/') + + async def test3(): + return await asession.get('https://smile.amazon.com/') + + r = asession.run(test1, test2, test3) + + assert len(r) == 3 + assert isinstance(r[0], HTMLResponse)