A Python library that provides an easy way to identify devices like mobile phones, tablets and their capabilities by parsing (browser) user agent strings.

Overview

Python User Agents

user_agents is a Python library that provides an easy way to identify/detect devices like mobile phones, tablets and their capabilities by parsing (browser/HTTP) user agent strings. The goal is to reliably detect whether:

  • User agent is a mobile, tablet or PC based device
  • User agent has touch capabilities (has touch screen)

user_agents relies on the excellent ua-parser to do the actual parsing of the raw user agent string.

Installation

Build status

user-agents is hosted on PyPI and can be installed as such:

pip install pyyaml ua-parser user-agents

Alternatively, you can also get the latest source code from Github and install it manually.

Usage

Various basic information that can help you identify visitors can be accessed browser, device and os attributes. For example:

from user_agents import parse

# iPhone's user agent string
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)

# Accessing user agent's browser attributes
user_agent.browser  # returns Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')
user_agent.browser.family  # returns 'Mobile Safari'
user_agent.browser.version  # returns (5, 1)
user_agent.browser.version_string   # returns '5.1'

# Accessing user agent's operating system properties
user_agent.os  # returns OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')
user_agent.os.family  # returns 'iOS'
user_agent.os.version  # returns (5, 1)
user_agent.os.version_string  # returns '5.1'

# Accessing user agent's device properties
user_agent.device  # returns Device(family=u'iPhone', brand=u'Apple', model=u'iPhone')
user_agent.device.family  # returns 'iPhone'
user_agent.device.brand # returns 'Apple'
user_agent.device.model # returns 'iPhone'

# Viewing a pretty string version
str(user_agent) # returns "iPhone / iOS 5.1 / Mobile Safari 5.1"

user_agents also expose a few other more "sophisticated" attributes that are derived from one or more basic attributes defined above. As for now, these attributes should correctly identify popular platforms/devices, pull requests to support smaller ones are always welcome.

Currently these attributes are supported:

  • is_mobile: whether user agent is identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)
  • is_tablet: whether user agent is identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)
  • is_pc: whether user agent is identified to be running a traditional "desktop" OS (Windows, OS X, Linux)
  • is_touch_capable: whether user agent has touch capabilities
  • is_bot: whether user agent is a search engine crawler/spider

For example:

from user_agents import parse

# Let's start from an old, non touch Blackberry device
ua_string = 'BlackBerry9700/5.0.0.862 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/331 UNTRUSTED/1.0 3gpp-gba'
user_agent = parse(ua_string)
user_agent.is_mobile # returns True
user_agent.is_tablet # returns False
user_agent.is_touch_capable # returns False
user_agent.is_pc # returns False
user_agent.is_bot # returns False
str(user_agent) # returns "BlackBerry 9700 / BlackBerry OS 5 / BlackBerry 9700"

# Now a Samsung Galaxy S3
ua_string = 'Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
user_agent = parse(ua_string)
user_agent.is_mobile # returns True
user_agent.is_tablet # returns False
user_agent.is_touch_capable # returns True
user_agent.is_pc # returns False
user_agent.is_bot # returns False
str(user_agent) # returns "Samsung GT-I9300 / Android 4.0.4 / Android 4.0.4"

# iPad's user agent string
ua_string = 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
user_agent = parse(ua_string)
user_agent.is_mobile # returns False
user_agent.is_tablet # returns True
user_agent.is_touch_capable # returns True
user_agent.is_pc # returns False
user_agent.is_bot # returns False
str(user_agent) # returns "iPad / iOS 3.2 / Mobile Safari 4.0.4"

# Kindle Fire's user agent string
ua_string = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true'
user_agent = parse(ua_string)
user_agent.is_mobile # returns False
user_agent.is_tablet # returns True
user_agent.is_touch_capable # returns True
user_agent.is_pc # returns False
user_agent.is_bot # returns False
str(user_agent) # returns "Kindle / Android / Amazon Silk 1.1.0-80"

# Touch capable Windows 8 device
ua_string = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; Touch)'
user_agent = parse(ua_string)
user_agent.is_mobile # returns False
user_agent.is_tablet # returns False
user_agent.is_touch_capable # returns True
user_agent.is_pc # returns True
user_agent.is_bot # returns False
str(user_agent) # returns "PC / Windows 8 / IE 10"

Running Tests

python -m unittest discover

Changelog

Version 2.2.0 (2020-08-23)

  • ua-parser >= 0.10.0 is required. Thanks @jnozsc!
  • Added get_device(), get_os() and get_browser() instance methods to UserAgent. Thanks @rodrigondec!

Version 2.1 (2020-02-08)

  • python-user-agents now require ua-parser>=0.9.0. Thanks @jnozsc!
  • Properly detect Chrome Mobile browser families. Thanks @jnozsc!

Version 2.0 (2019-04-07)

  • python-user-agents now require ua-parser>=0.8.0. Thanks @IMDagger!

Version 1.1

  • Fixes packaging issue

Version 1.0

  • Adds compatibility with ua-parser 0.4.0
  • Access to more device information in user_agent.device.brand and user_agent.device.model

Version 0.3.2

  • Better mobile detection
  • Better PC detection

Version 0.3.1

  • user_agent.is_mobile returns True when mobile spider is detected

Version 0.3.0

  • Added str/unicode methods for convenience of pretty string

Version 0.2.0

  • Fixed errors when running against newer versions if ua-parser
  • Support for Python 3

Version 0.1.1

  • Added is_bot property
  • Symbian OS devices are now detected as a mobile device

Version 0.1

  • Initial release

Developed by the cool guys at Stamps.

Comments
  • Add Chromebook detection as a

    Add Chromebook detection as a "pc"

    Given Chromebooks are laptops, treat them as is done for MacBooks - "PC" category.

    The new test for this passes but pre-existing test for iPad is failing.

    opened by kulor 9
  • Surface tablets are seen as non-touch-capable pc

    Surface tablets are seen as non-touch-capable pc

    I'm having an issue with a Surface. User agent is Mozilla/5.0 (Windows NT 6.3; ARM; Trident/7.0; Touch; rv:11.0 and it's not detexcted as a touch-capable device:

    {'device': Device(family='Other'), 'browser': Browser(family=u'IE', version=(11,), version_string='11'), 'os': OperatingSystem(family='Windows', version=(), version_string=''), 'ua_string': 'Mozilla/5.0 (Windows NT 6.3; ARM; Trident/7.0; Touch; rv:11.0) like Gecko'}

    opened by qur2 8
  • _is_android_tablet was detecting Opera Mini as Tablet fixed now

    _is_android_tablet was detecting Opera Mini as Tablet fixed now

    Opera Mini mobile browser is wrongly detected as Tablet. is_tablet() internally uses _is_android_tablet() which was detecting "Opera Mini" as Tablet, this is fixed in this pull request.

    opened by shivamsupr 6
  • dont work on ubuntu 14.04

    dont work on ubuntu 14.04

    i install ua-parser and user-agents on ubuntu via pip ...

    but when i run python script always get me error

    ua = parse('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') File "/usr/local/lib/python2.7/dist-packages/user_agents/parsers.py", line 205, in parse return UserAgent(user_agent_string) File "/usr/local/lib/python2.7/dist-packages/user_agents/parsers.py", line 113, in init self.device = parse_device(**ua_dict['device']) TypeError: parse_device() got an unexpected keyword argument 'brand'

    opened by abbas-h 6
  • method __str__() from UserAgent now using methods custom get_device, get_os and get_browser

    method __str__() from UserAgent now using methods custom get_device, get_os and get_browser

    Is better to calculate and provide a method to calculate the string values for device, os and browser instead of doing it directly on __str__ method.

    This way the users may use those methods to get each data directly. Instead of having to make a user_agent.__str__().split('/') to get each value.

    opened by rodrigondec 5
  • Preserve minor and patch version even if they are zeros

    Preserve minor and patch version even if they are zeros

    The current logic drops the minor and patch version if they are zeros.

    E.g. '10.0' becomes '10' and '5.0.0' becomes '5'

    Those info are sometimes useful for doing version comparison

    opened by uaymas 4
  • Fix Firefox Tablet classification.

    Fix Firefox Tablet classification.

    With the latest uap-core changes, Firefox for Android on tablets is identified as Firefox Mobile and therefore we need to update code to check if device is Mobile or Tablet.

    See: https://github.com/ua-parser/uap-core/commit/98d29ff4dbab665e380ef0c7eaeeecb6afce425c

    opened by glogiotatidis 4
  • Android 9 os version empty

    Android 9 os version empty

    Hello,

    When I parse the below user agent, it returns empty. Although it should return 9.

    Dalvik/2.1.0 (Linux; U; Android 9; SM-G965U Build/PPR1.180610.011)

    opened by ardaguclu 3
  • Pin ua-parser to <0.4.0

    Pin ua-parser to <0.4.0

    ua-parser 0.4.0 has just been released, and the lack of pinning here breaks apps that don't explicitly pin their dependencies. Don't know if this is the right place / way to pin this, but it would definitely improve the situation.

    opened by abesto 3
  • mobile spiders should be considered mobile

    mobile spiders should be considered mobile

    Google don't wanna be treated different than a normal user. As google sets its user agent browser to "Mobile Safari" it have to be detected as 'is_mobile'.

    opened by paepke 3
  • Internet Explorer 11

    Internet Explorer 11

    sadly, IE11 is detected as 'other'

    Browser(family='Other', version=(), version_string='')

    here is the link:

    http://msdn.microsoft.com/library/ie/hh869301(v=vs.85).aspx

    opened by abdelouahabb 3
  • PetalBot not identified as bot

    PetalBot not identified as bot

    I have got several accesses from Petal Search bot PetalBot which are not identified as bots. It is identified with following User Agent:

    Mozilla/5.0 (Linux; Android 7.0;) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; PetalBot;+https://webmaster.petalsearch.com/site/petalbot)
    
    opened by PetrDlouhy 0
  • Dalvik browser on Android is identified as a tablet

    Dalvik browser on Android is identified as a tablet

    I just bumped into some user-agents that have an explicit mobile phone name stated but still detected as a tablet. Here are some examples:

    Dalvik/1.6.0 (Linux; U; Android 4.4.4; GT-I9195I Build/KTU84P)
    Dalvik/2.1.0 (Linux; U; Android 10; ASUS_I003DD Build/QKQ1.200419.002)
    Dalvik/2.1.0 (Linux; U; Android 10; BLA-L09 Build/HUAWEIBLA-L09S)
    Dalvik/2.1.0 (Linux; U; Android 10; ELE-L29 Build/HUAWEIELE-L29)
    Dalvik/2.1.0 (Linux; U; Android 10; Redmi Note 8 Pro MIUI/V12.0.8.0.QGGMIXM)
    

    Any idea how to fix this ? I can work on a PR, but I didn't found how to fix this without implementing a list of valid phone names or regexes which seems quite overkill...

    opened by vparpoil 0
  • VIZIO SmartCast User Agents Incorrectly Parsed as PC Devices

    VIZIO SmartCast User Agents Incorrectly Parsed as PC Devices

    VIZIO SmartCast User Agents are being incorrected labeled as with True for the is_pc property in the code below:

    https://github.com/selwin/python-user-agents/blob/862c54baf1e6dd095390a8ebfdd3f5303a5b0a32/user_agents/parsers.py#L264

    Examples of these user agents:

    Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36 CrKey/1.0.999999 VIZIO SmartCast(Conjure/SX7B-2.0.9.0 FW/5.0.5.2 Model/E43-F1)
    Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36 CrKey/1.0.999999 VIZIO SmartCast(Conjure/MTKA-1.4.39.3 FW/4.50.18 Model/D32h-F4),gzip(gfe),gzip(gfe)
    Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36 CrKey/1.0.999999 VIZIO SmartCast(Conjure/MTKD-7.520.90.0-qa FW/5.520.23.2-v-2 Model/P65Q9-J01)
    

    It looks like because these user agents satisfies the both the "Linux" and "X11" conditions the logic is incorrectly classifying them as PC.

    opened by jesseginsberg 0
  • Spider/Crawler Google Favicon not detected as  Spider

    Spider/Crawler Google Favicon not detected as Spider

    Google Favicon is the user agent for downloading favicons defined by websites. https://developers.google.com/search/docs/advanced/appearance/favicon-in-search#crawler

    Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)  Chrome/49.0.2623.75 Safari/537.36 Google Favicon
    
    opened by kojibhy 0
Releases(v2.2.0)
  • v2.2.0(Aug 23, 2020)

    • ua-parser >= 0.10.0 is required. Thanks @jnozsc!
    • Added get_device(), get_os() and get_browser() instance methods to UserAgent. Thanks @rodrigondec!
    Source code(tar.gz)
    Source code(zip)
Owner
Selwin Ong
Selwin Ong
RSS Reader application for the Emacs Application Framework.

EAF RSS Reader RSS Reader application for the Emacs Application Framework. Load application (add-to-list 'load-path "~/.emacs.d/site-lisp/eaf-rss-read

EAF 15 Dec 07, 2022
Python Lex-Yacc

PLY (Python Lex-Yacc) Copyright (C) 2001-2020 David M. Beazley (Dabeaz LLC) All rights reserved. Redistribution and use in source and binary forms, wi

David Beazley 2.4k Dec 31, 2022
The project is investigating methods to extract human-marked data from document forms such as surveys and tests.

The project is investigating methods to extract human-marked data from document forms such as surveys and tests. They can read questions, multiple-choice exam papers, and grade.

Harry 5 Mar 27, 2022
A minimal code sceleton for a textadveture parser written in python.

Textadventure sceleton written in python Use with a map file generated on https://www.trizbort.io Use the following Sockets for walking directions: n

1 Jan 06, 2022
Extract price amount and currency symbol from a raw text string

price-parser is a small library for extracting price and currency from raw text strings.

Scrapinghub 252 Dec 31, 2022
Meeting, rendezvous, confluence (Finnish kohtaaminen) mark up, down, and up again.

kohtaaminen Meeting, rendezvous, confluence (Finnish kohtaaminen) mark up, down, and up again. Given a zip file containing a tree of html and media fi

Stefan Hagen 2 Dec 14, 2022
This repos is auto action which generating a wordcloud made by Twitter.

auto_tweet_wordcloud This repos is auto action which generating a wordcloud made by Twitter. Preconditions Install Python dependencies pip install -r

tubone(Yu Otsubo) 0 Apr 29, 2022
Fixes mojibake and other glitches in Unicode text, after the fact.

ftfy: fixes text for you print(fix_encoding("(ง'⌣')ง")) (ง'⌣')ง Full documentation: https://ftfy.readthedocs.org Testimonials “My life is li

Luminoso Technologies, Inc. 3.4k Jan 08, 2023
"Complexity" of Flags of the countries of the world

"Complexity" of Flags of the countries of the world Flags (png) from: https://flagcdn.com/w2560.zip https://flagpedia.net/download/images run: chmod +

Alexander Lelchuk 1 Feb 10, 2022
WorldCloud Orçamento de Estado 2022

World Cloud Orçamento de Estado 2022 What it does This script creates a worldcloud, masked on a image, from a txt file How to run it? Install all libr

Jorge Gomes 2 Oct 12, 2021
Migrates translations to the REDCap native Multi-Language Management system

Automates much of the process of moving translations from the old Multilingual external module to the newer built-in Multi-Language Management (MLM) page.

UCI MIND 3 Sep 27, 2022
Word-Generator - Generates meaningful words from dictionary with given no. of letters and words.

Meaningful Word Generator Generates meaningful words from dictionary with given no. of letters and words. This might be useful for generating short li

Mohammed Rabil 1 Jan 01, 2022
An extension to detect if the articles content match its title.

Clickbait Detector An extension to detect if the articles content match its title. This was developed in a period of 24-hours in a hackathon called 'H

Arvind Krishna 5 Jul 26, 2022
Convert text to morse code and play morse code sound.

Convert text(english) to morse codes and play morse sound!

Mohammad Dori 5 Jul 15, 2022
A Python package to facilitate research on building and evaluating automated scoring models.

Rater Scoring Modeling Tool Introduction Automated scoring of written and spoken test responses is a growing field in educational natural language pro

ETS 59 Oct 10, 2022
Answer some questions and get your brawler csvs ready!

BRAWL-STARS-V11-BRAWLER-MAKER-TOOL Answer some questions and get your brawler csvs ready! HOW TO RUN on android: Install pydroid3 from playstore, and

9 Jan 07, 2023
Python library for creating PEG parsers

PyParsing -- A Python Parsing Module Introduction The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the t

Pyparsing 1.7k Dec 27, 2022
Free & simple way to encipher text

VenSipher VenSipher is a free medium through which text can be enciphered. It can convert any text into an unrecognizable secret text that can only be

3 Jan 28, 2022
A slugifier that works in unicode

Unicode Slugify Unicode Slugify is a slugifier that generates unicode slugs. It was originally used in the Firefox Add-ons web site to generate slugs

Mozilla 315 Nov 21, 2022