Skip to content

Instantly share code, notes, and snippets.

@franccesco
Created September 19, 2019 21:31
Show Gist options
  • Save franccesco/6f14bdc51a2ca5d96cf8332a7f5ccafb to your computer and use it in GitHub Desktop.
Save franccesco/6f14bdc51a2ca5d96cf8332a7f5ccafb to your computer and use it in GitHub Desktop.
Asynchronous example on how to perform multiple requests using AioHTTP and Asyncio
import asyncio
import aiohttp
from bs4 import BeautifulSoup
async def get_title(session, url):
async with session.get(url) as response:
html_source = await response.text()
soup = BeautifulSoup(html_source, "html.parser")
return soup.title.text
async def main():
url_list = [
'https://codingdose.info/2019/06/26/Save-your-dictionaries-lists-tuples-and-other-objects-with-Pickle/',
'https://codingdose.info/2019/06/16/develop-and-publish-with-poetry/',
'https://codingdose.info/2019/06/15/how-to-use-a-progress-bar-in-python/',
'https://codingdose.info/2019/06/08/create-a-project-page-for-your-repositories-easily-with-Jekyll/',
'https://codingdose.info/2019/03/06/How-to-create-a-Ruby-gem-with-Bundler/',
'https://codingdose.info/2018/08/06/Generate-and-sign-your-commits-with-GPG-in-Github/',
'https://codingdose.info/2018/05/12/change-flask-root-folder/',
'https://codingdose.info/2018/05/10/deploy-a-flask-project-to-heroku/',
'https://codingdose.info/2018/05/05/ipchallenge-part-3/',
'https://codingdose.info/2018/05/03/ipchallenge-part-2/',
'https://codingdose.info/2018/05/02/Challenge-IPInfo-io-Class/',
'https://codingdose.info/2018/05/01/announcement-about-lack-of-activity/',
'https://codingdose.info/2018/04/17/case-import-variables-from-a-web-site-Python/',
'https://codingdose.info/2018/04/17/create-multiple-directories-with-makedirs-Python/',
'https://codingdose.info/2018/04/14/Deques-in-Python/'
]
async with aiohttp.ClientSession() as session:
coroutines = [get_title(session, url) for url in url_list]
coroutines_result = await asyncio.gather(*coroutines)
for task in coroutines_result:
print(task)
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment