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.
pip install user-agentsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to parse different user agent strings using `user_agents.parse` and access various properties like device type, operating system, and browser information. It also shows how the library handles empty strings gracefully, returning an object with 'Other' or empty values.
Ensure your `ua-parser` dependency is updated to at least `0.10.0` or allow pip to upgrade it automatically (`pip install --upgrade user-agents`). Consider using a virtual environment to manage dependencies.
Always check the returned `UserAgent` object's properties (e.g., `user_agent.is_unknown` or `user_agent.device.family == 'Other'`) if you need to specifically handle empty or unidentifiable user agents. You may want to implement explicit checks for empty strings before calling `parse()` if an error is preferred.
Regularly upgrade the `user-agents` package (`pip install --upgrade user-agents`) to ensure you have the latest `ua-parser` definitions available. The `user-agents` library's `install_requires` ensures a compatible `ua-parser` version is installed.
Install the library using pip: `pip install user-agents`
Access these attributes directly without parentheses: `if user_agent.is_mobile: ...`
Either import `parse` directly: `from user_agents import parse` and then use `parse(ua_string)`, or use `user_agents.parse(ua_string)` after `import user_agents`.
First, parse the user agent string to get a `UserAgent` object, then access its attributes: `user_agent = parse(ua_string); print(user_agent.browser.family)`