Random User Agent Simulation in Locust

  • Share this:

Code introduction


This code defines a Locust user simulation class that simulates the random selection of user agents and prints them out.


Technology Stack : Locust, random choice, user agent simulation

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_user_agent(user_id):
    import random
    from locust import Locust, task

    class User(Locust):
        task_set = [random_user_agent_task]

        @task
        def random_user_agent_task(self):
            agent = self.get_random_user_agent()
            print(f"User {self.user_id} is using user agent: {agent}")

        def get_random_user_agent(self):
            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 (Linux; Android 10; SM-A505FN) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Mobile Safari/537.36",
                "Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
            ]
            return random.choice(agents)