Created
June 21, 2025 12:09
-
-
Save Pymmdrza/5ea35722c8a0f6d0f75756ba9acbb30f to your computer and use it in GitHub Desktop.
Generate random user agent in python without any extra packages π¦
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# credit by : Pymmdrza.github.io | |
import random | |
from datetime import date | |
OS_CHOICES = { | |
"Macintosh": ["68K", "PPC", "Intel Mac OS X"], | |
"Windows": [ | |
"Win3.11", | |
"WinNT3.51", | |
"WinNT4.0", | |
"Windows NT 5.0", | |
"Windows NT 5.1", | |
"Windows NT 5.2", | |
"Windows NT 6.0", | |
"Windows NT 6.1", | |
"Windows NT 6.2", | |
"Win 9x 4.90", | |
"WindowsCE", | |
"Windows XP", | |
"Windows 7", | |
"Windows 8", | |
"Windows NT 10.0; Win64; x64", | |
], | |
"X11": ["Linux i686", "Linux x86_64"], | |
} | |
def _generate_chrome(os_string): | |
"""Generates a Chrome User-Agent string.""" | |
webkit_version = random.randint(500, 599) | |
chrome_version = ( | |
f"{random.randint(0, 99)}.0.{random.randint(0, 9999)}.{random.randint(0, 999)}" | |
) | |
return ( | |
f"Mozilla/5.0 ({os_string}) AppleWebKit/{webkit_version}.0 (KHTML, like Gecko) " | |
f"Chrome/{chrome_version} Safari/{webkit_version}" | |
) | |
def _generate_firefox(os_string): | |
"""Generates a Firefox User-Agent string.""" | |
today = date.today() | |
gecko_trail = f"{random.randint(2020, today.year)}{random.randint(1, 12):02d}{random.randint(1, 30):02d}" | |
firefox_version = f"{random.randint(1, 72)}.0" | |
return ( | |
f"Mozilla/5.0 ({os_string}; rv:{firefox_version}) " | |
f"Gecko/{gecko_trail} Firefox/{firefox_version}" | |
) | |
def _generate_ie(os_string): | |
"""Generates an Internet Explorer User-Agent string.""" | |
ie_version = f"{random.randint(1, 99)}.0" | |
trident_version = f"{random.randint(1, 99)}.0" | |
token = "" | |
if random.choice([True, False]): | |
token = ( | |
random.choice( | |
[ | |
".NET CLR", | |
"SV1", | |
"Tablet PC", | |
"Win64; IA64", | |
"Win64; x64", | |
"WOW64", | |
] | |
) | |
+ "; " | |
) | |
return ( | |
f"Mozilla/5.0 (compatible; MSIE {ie_version}; {os_string}; " | |
f"{token}Trident/{trident_version})" | |
) | |
BROWSER_GENERATORS = { | |
"chrome": _generate_chrome, | |
"firefox": _generate_firefox, | |
"ie": _generate_ie, | |
} | |
def getuseragent(): | |
""" | |
Generates a random User-Agent string. | |
""" | |
platform = random.choice(list(OS_CHOICES.keys())) | |
os_string = random.choice(OS_CHOICES[platform]) | |
browser = random.choice(list(BROWSER_GENERATORS.keys())) | |
return BROWSER_GENERATORS[browser](os_string) | |
# Example usage: | |
# from useragent_file_name import getuseragent | |
# print(getuseragent()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment