Random User-Agent Middleware for Aiohttp-web

  • Share this:

Code introduction


This function uses the Aiohttp-web library to create a middleware that can randomly change the User-Agent header of requests, used to simulate different browsers.


Technology Stack : Aiohttp-web

Code Type : Web middleware

Code Difficulty : Intermediate


                
                    
def random_user_agent(request):
    import aiohttp
    import random
    from aiohttp import web

    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Safari/605.1.15",
        "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0",
        "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
    ]

    @web.middleware
    async def middleware(request):
        user_agent = random.choice(user_agents)
        request.headers['User-Agent'] = user_agent
        return await request.next()

    return web.Middleware(middleware)                
              
Tags: