PyMobileDetect
PyMobileDetect is a Python library that detects mobile and tablet browsers based on the User-Agent string. It is a port of the popular PHP Mobile Detect library. The current version is 1.3.2, with releases being infrequent but stable, primarily aligning with updates to the underlying detection rules.
Common errors
-
ModuleNotFoundError: No module named 'pymobiledetect'
cause Attempting to import from 'pymobiledetect' directly, instead of 'mobiledetect'.fixChange your import statement from `from pymobiledetect import MobileDetect` to `from mobiledetect import MobileDetect`. -
TypeError: MobileDetect() missing 1 required positional argument: 'user_agent'
cause The `MobileDetect` class requires a User-Agent string upon instantiation.fixProvide a User-Agent string when creating an instance, e.g., `detector = MobileDetect(user_agent='...')`. In web applications, this typically comes from `request.headers['User-Agent']`. -
My new device is detected as desktop/generic, but it's a mobile!
cause The installed version of `pymobiledetect` might not have the latest detection rules for very new devices or browser versions.fixEnsure you have the latest version of `pymobiledetect` installed via `pip install --upgrade pymobiledetect`. If the issue persists, the underlying detection rules (inherited from the PHP project) might not yet include data for your specific device.
Warnings
- gotcha The package name on PyPI is `pymobiledetect`, but the Python module you need to import is `mobiledetect`. Importing directly from `pymobiledetect` will result in a `ModuleNotFoundError`.
- gotcha The detection rules are static within the installed library version and do not auto-update. Newer devices, operating systems, or browser versions released after the library's last update might not be correctly identified.
- gotcha Detection accuracy is entirely dependent on the provided User-Agent string. Spoofed, incomplete, or malformed User-Agents will lead to incorrect or failed detection.
Install
-
pip install pymobiledetect
Imports
- MobileDetect
from pymobiledetect import MobileDetect
from mobiledetect import MobileDetect
Quickstart
from mobiledetect import MobileDetect
# Simulate a User-Agent string (e.g., from an HTTP request header)
# In a web framework, you would get this from request.headers.get('User-Agent', '')
user_agent = 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Mobile Safari/537.36'
detector = MobileDetect(user_agent=user_agent)
if detector.is_mobile():
print("This is a mobile device.")
elif detector.is_tablet():
print("This is a tablet device.")
else:
print("This is a desktop device.")
# Check for specific properties
if detector.is_android():
print("Operating system: Android")
if detector.is_chrome():
print("Browser: Chrome")