Detecting Browsers in Python
dave at pythonapocrypha.com
Tue Nov 18 18:03:28 CET 2003
> Does anyone know of a simple way to have a Python script find out what
> browser is accessing it? After a web search the only thing I found to
> do this is Zope, but the system I'm programming doesn't use Zope and
> I'm not really interested in installing it just for this minor detail.
> Is there another way?
(I assume you mean that the script the browser is accessing is a CGI script)
Most browsers include a "User-Agent" in the HTTP request they make to a server.
Users can override these, but few people do, so you can semi-reliably detect
the browser that way.
I sometimes need to make sure a browser is running on "new enough" Windows, so
I use this:
ua = ua.lower()
if ua.find('win') != -1 and ua.find('win16') == -1 and \
ua.find('windows nt 4') == -1 and ua.find('winnt4') == -1:
# platform is Windows
# non-Windows or old Windows
As for browser vendor, this is the pseudocode I use:
if ua.find('opera') != -1:
elif ua.find('gecko') != -1:
# gecko (moz/ns)
elif ua.find('msie') != -1:
# Most likely really is IE
# somebody else
This works for what I need because usually I'm just trying to acertain if the
browser is IE on a newer Windows box, but you may need additional checks
(Google can turn up huge lists of all known default User-Agent strings so it's
fairly easy to come up with a good test suite).
More information about the Python-list