Random User Agent Fetcher with Aiohttp

  • Share this:

Code introduction


This function uses the Aiohttp library to fetch a random user agent string from the randomuser.me API.


Technology Stack : Aiohttp, asyncio, random

Code Type : Asynchronous HTTP request

Code Difficulty : Intermediate


                
                    
def random_user_agent():
    import aiohttp
    import asyncio
    import random

    async def fetch_user_agent(session):
        url = 'https://api.randomuser.me/'
        async with session.get(url) as response:
            return await response.json()

    async def main():
        async with aiohttp.ClientSession() as session:
            data = await fetch_user_agent(session)
            user_agent = data['results'][0]['browser']['userAgent']
            return user_agent

    loop = asyncio.get_event_loop()
    user_agent = loop.run_until_complete(main())
    return user_agent