httpagentparser
httpagentparser is a Python library (current version 1.9.9) that efficiently extracts operating system, browser, and other relevant information from HTTP User-Agent strings. It offers fast parsing and is primarily focused on detecting OS and browser details rather than being a full-featured agent parser. Releases are infrequent but have recently addressed maintenance and optimization.
Warnings
- gotcha The `detect()` method returns a standard Python dictionary. The order of keys in dictionaries is not guaranteed across Python versions or runs, which can lead to unexpected output order if you rely on it for consistent string representation or comparison.
- gotcha The library explicitly states it 'Does not aim to be a full featured agent parser.' It is optimized for fast OS and browser detection but may not provide granular device details, comprehensive bot detection, or cover all obscure user-agent strings as thoroughly as more extensive or commercial solutions.
- gotcha Older versions (e.g., 1.9.5) sometimes encountered `setup.py egg_info` errors during installation in certain environments, often related to setuptools packaging issues.
Install
-
pip install httpagentparser
Imports
- httpagentparser
import httpagentparser
Quickstart
import httpagentparser
# Example user agent string
user_agent_string = "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/532.9 (KHTML, like Gecko) Chrome/5.0.307.11 Safari/532.9"
# Basic detection returning (OS, Browser) tuple
simple_result = httpagentparser.simple_detect(user_agent_string)
print(f"Simple Detection (OS, Browser): {simple_result}")
# Detailed detection returning a dictionary
detailed_result = httpagentparser.detect(user_agent_string)
print(f"Detailed Detection: {detailed_result}")
# Accessing specific parts of the detailed result
if detailed_result.get('os'):
print(f"OS Name: {detailed_result['os'].get('name')}")
if detailed_result.get('browser'):
print(f"Browser Name: {detailed_result['browser'].get('name')}")
print(f"Browser Version: {detailed_result['browser'].get('version')}")
# Example with a mobile user agent
mobile_ua = "Mozilla/5.0 (Linux; U; Android 2.3.5; en-in; HTC_DesireS_S510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"
mobile_result = httpagentparser.detect(mobile_ua)
print(f"\nMobile User Agent Detailed Detection: {mobile_result}")
if mobile_result.get('dist'):
print(f"Mobile OS Distribution: {mobile_result['dist'].get('name')} {mobile_result['dist'].get('version')}")