When making requests in Python, you may sometimes want them to appear as if they are coming from a mobile device rather than a desktop computer. This allows you to test how your web application responds to mobile devices, ensures you receive the mobile version of sites, or can even get around blocks on desktop user agents.
There are a few simple steps to making Python requests appear as mobile:
Set a Mobile User-Agent Header
The main thing that identifies requests as mobile vs desktop is the
To make a request appear as an iPhone, you can set the User-Agent to a common iPhone value:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 Mobile/15E148 Safari/604.1'}
resp = requests.get('https://example.com', headers=headers)
Use a Mobile HTTP Client Library
Some Python libraries, like python-user-agents, make it easy to generate and use random mobile user agents.
Proxy Through a Mobile Device
Another approach is to proxy your Python script's requests through an actual mobile device to inherit its user agent and other mobile characteristics. Tools like browserless make this easy to set up.
The main thing is to ensure the User-Agent header accurately represents a mobile device. Doing this along with other mobile-specific behaviors like touch events and screen size can make your Python requests blend in seamlessly with genuine mobile traffic.