fake-useragent
fake-useragent is a Python library that generates up-to-date and realistic browser user-agent strings for web scraping and testing purposes. It dynamically fetches a database of real-world user agents to provide diverse and current options. The current version is 2.2.0, with minor releases occurring every few months to update the user-agent database or fix small issues.
Warnings
- breaking Since version 2.0.0, OS and browser options are case-sensitive. Previously, they might have been implicitly converted or handled with more flexibility.
- breaking In version 2.0.0, the `platform` type value 'pc' was changed to 'desktop'. If you were specifically requesting desktop user agents using `platform='pc'`, your code will no longer work as expected.
- gotcha Since version 1.5.0, the `min_percentage` parameter for filtering user agents is effectively useless. The new data sources introduced in this version and later do not provide usage statistics, so this filter is ignored.
- gotcha fake-useragent requires Python 3.9 or newer since version 2.0.1. Attempting to use it with older Python versions will result in compatibility errors.
- gotcha On its first run (or when the cache expires), `fake-useragent` attempts to download a JSON file (~500KB) from an external source (currently intoli.com). This can introduce network delays, fail due to connectivity issues, or be blocked by firewalls/proxies.
Install
-
pip install fake-useragent
Imports
- UserAgent
from fake_useragent import UserAgent
- FakeUserAgentError
from fake_useragent import FakeUserAgentError
Quickstart
from fake_useragent import UserAgent, FakeUserAgentError
try:
ua = UserAgent()
print(f"Random User-Agent: {ua.random}")
print(f"Chrome User-Agent: {ua.chrome}")
print(f"Firefox User-Agent: {ua.firefox}")
print(f"User-Agent for macOS: {ua.get_ua('chrome', os='macos')}")
print(f"User-Agent for desktop: {ua.get_ua(platform='desktop')}")
except FakeUserAgentError as e:
print(f"Error fetching user agents: {e}")
print("This might be due to network issues or the first-time data download failing.")