User-Agents Library
The `user-agents` library is a simple Python library for identifying devices (phones, tablets, PCs) and their capabilities by parsing browser user agent strings. It wraps the `ua-parser` library and provides a more convenient object-oriented interface. The current version is 2.2.0, and releases are made periodically to incorporate updates from `ua-parser` and add minor features.
Warnings
- breaking Version 2.2.0 and newer explicitly require `ua-parser >= 0.10.0`. If you have an older version of `ua-parser` pinned in your environment, upgrading `user-agents` might lead to dependency conflicts or installation failures.
- gotcha Parsing an empty or `None` user agent string does not raise an error. Instead, `parse('')` returns a `UserAgent` object where properties like `is_pc`, `is_mobile`, `browser.family`, `os.family`, etc., will default to `False`, `None`, or 'Other'/'Unknown' respectively. This might not be the expected behavior for users anticipating an error or `None`.
- gotcha The underlying user agent definitions are provided by the `ua-parser` library. For the most accurate and up-to-date parsing, it's crucial that `ua-parser` (and thus `user-agents`) is kept up-to-date. Outdated versions may incorrectly identify newer devices or browsers.
Install
-
pip install user-agents
Imports
- parse
from user_agents import parse
Quickstart
from user_agents import parse
# Example user agent strings
user_agent_string_mobile = 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36'
user_agent_string_desktop = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
user_agent_string_empty = ''
# Parse a mobile user agent
user_agent_mobile = parse(user_agent_string_mobile)
print(f"Mobile UA: {user_agent_mobile.is_mobile} (Mobile)")
print(f"Device: {user_agent_mobile.device.family}, OS: {user_agent_mobile.os.family} {user_agent_mobile.os.version_string}")
print(f"Browser: {user_agent_mobile.browser.family} {user_agent_mobile.browser.version_string}\n")
# Parse a desktop user agent
user_agent_desktop = parse(user_agent_string_desktop)
print(f"Desktop UA: {user_agent_desktop.is_pc} (PC)")
print(f"Device: {user_agent_desktop.device.family}, OS: {user_agent_desktop.os.family} {user_agent_desktop.os.version_string}")
print(f"Browser: {user_agent_desktop.browser.family} {user_agent_desktop.browser.version_string}\n")
# Parse an empty user agent
user_agent_empty = parse(user_agent_string_empty)
print(f"Empty UA is_pc: {user_agent_empty.is_pc}")
print(f"Empty UA device family: {user_agent_empty.device.family}")