python-user-agents

repository·master·Indexed 23 days ago

https://github.com/selwin/python-user-agents

A Python library for identifying and detecting devices (mobile, tablet, PC) and their capabilities by parsing HTTP user agent strings. It provides a UserAgent object with detailed attributes for browser, operating system, and device families, as well as boolean flags for is_mobile, is_tablet, is_pc, is_touch_capable, and is_bot.

Tokens
727
Snippets
3
Records
5
Agent score
31%

What's inside python-user-agents

  1. Get a pretty string representation of a UserAgent

    master

    You can convert a UserAgent object into a human-readable string using the built-in str() function. The format is typically Device / OS / Browser.

    from user_agents import parse
    
    ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'
    user_agent = parse(ua_string)
    
    print(str(user_agent)) # returns "iPhone / iOS 5.1 / Mobile Safari 5.1"
  2. Parse a user agent string with parse()

    master

    Use the parse function from user_agents to convert a raw HTTP user agent string into a UserAgent object. This object allows you to access detailed information about the browser, operating system, and device.

    from user_agents import parse
    
    ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'
    user_agent = parse(ua_string)
  3. Identify device types using boolean attributes

    master

    The UserAgent object provides high-level boolean attributes to quickly categorize the visitor:

    • is_mobile: True if the user agent is a mobile phone (e.g., iPhone, Android phone, Blackberry).
    • is_tablet: True if the user agent is a tablet (e.g., iPad, Kindle Fire).
    • is_pc: True if the user agent is running a traditional desktop OS (e.g., Windows, OS X, Linux).
    • is_touch_capable: True if the device has touch screen capabilities.
    • is_bot: True if the user agent is a search engine crawler or spider.
  4. Access browser, OS, and device attributes

    master

    Once parsed, you can access specific properties of the user agent:

    Browser attributes

    • user_agent.browser.family: The browser family (e.g., 'Mobile Safari').
    • user_agent.browser.version: A tuple representing the version (e.g., (5, 1)).
    • user_agent.browser.version_string: The version as a string (e.g., '5.1').

    Operating System attributes

    • user_agent.os.family: The OS family (e.g., 'iOS').
    • user_agent.os.version: A tuple representing the OS version.
    • user_agent.os.version_string: The OS version as a string.

    Device attributes

    • user_agent.device.family: The device family (e.g., 'iPhone').
    • user_agent.device.brand: The device brand (e.g., 'Apple').
    • user_agent.device.model: The device model (e.g., 'iPhone').