Using python-user-agents to Parse Browser User-Agent Strings
This guide introduces the python-user-agents library, showing how to install it, import and use its parse function to extract browser, operating system, device, and bot information from User-Agent strings, and demonstrates advanced custom data handling and real‑world application scenarios.
Introduction python-user-agents is a Python library for parsing browser User-Agent strings, allowing extraction of browser, operating system, device type, and bot information, which is useful for web log analysis and client‑aware applications.
Installation You can install the library via pip:
pip install pyyaml ua-parser user-agentsBasic Usage First import the required function:
from user_agents import parseParsing a User-Agent String Use the parse function to analyze a User-Agent string and retrieve details:
# Example User-Agent string
user_agent_string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
# Parse the User-Agent string
user_agent = parse(user_agent_string)
# Print parsed results
print("Browser Family:", user_agent.browser.family) # Browser family
print("Browser Version:", user_agent.browser.version_string) # Browser version
print("Operating System Family:", user_agent.os.family) # OS family
print("Operating System Version:", user_agent.os.version_string) # OS version
print("Device Family:", user_agent.device.family) # Device family
print("Is Mobile:", user_agent.is_mobile) # Mobile flag
print("Is Tablet:", user_agent.is_tablet) # Tablet flag
print("Is PC:", user_agent.is_pc) # PC flag
print("Is Bot:", user_agent.is_bot) # Bot flagSample Output Running the above code may produce output similar to:
Browser Family: Chrome
Browser Version: 91.0.4472.124
Operating System Family: Windows
Operating System Version: 10
Device Family: Other
Is Mobile: False
Is Tablet: False
Is PC: True
Is Bot: FalseAdvanced Usage – Custom User-Agent Data If you have a custom User-Agent data file, you can load and parse it using pyyaml and ua_parser :
import yaml
from ua_parser import user_agent_parser
# Load custom User-Agent data file
with open('custom_user_agents.yaml', 'r') as f:
custom_ua_data = yaml.safe_load(f)
# Parse User-Agent string with custom data
parsed_ua = user_agent_parser.Parse(user_agent_string, **custom_ua_data)
print(parsed_ua)Real‑World Application Scenarios - Web log analysis: Identify browsers, OS, and devices from server logs. - Responsive design: Serve different layouts based on device type. - Content adaptation: Tailor content to specific browsers or operating systems. - Security detection: Detect and block malicious bots or crawlers.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.