HTTP_USER_AGENT Parsing

brueckd at tbye.com brueckd at tbye.com
Wed Jul 17 11:13:06 EDT 2002


On Tue, 16 Jul 2002, Olly Smith wrote:

> > > I'm a bit of a newbie to Python, and in my quest to generate nice HTML
> > > content, I need a way to work out what browsers clients are using from
> their
> > > HTTP_USER_AGENT strings.
> > >
> > > Any pointers?
[snip]
> Ta, I'll check that out.  This bit of code I'm working on has to produce a
> 'nice' interface, but part of the spec says it must work with NS4 correctly
> .. and we all know NS4 is a PITA ;)

Ugh, I feel your pain! I once worked on a project that had the same 
requirement, and after wasting way too much time on NS4 compatibility we 
as a team revolted and got the requirement dropped. :)

Anyway, if you only have to differentiate between NS4 and "everything
else" (ie - you have the HTML you'll generate normally and then some
different stuff iff the browser is NS4) then you can probably get by with
something simpler than parsing the entire user agent string - just do some
substring searches. You'll want to verify this yourself with a decent set
of browsers, but something like this would work:

(assume UA = the user agent string)
UA = UA.lower()
if UA.find('mozilla/4.0') != -1 and
   UA.find('opera') == -1 and
   UA.find('msie') == -1 and
   UA.find('konq') == -1:
 # Probably Netscape 4
else:
 # Probably not Netscape 4

This is much shorter than actually parsing the user agent string, and just
about as accurate (besides, you can't feel TOO much sympathy for somebody
who is using a non-NS4 browser that reports itself as NS4! :) ).

-Dave






More information about the Python-list mailing list