Grabbing user's agent and OS type

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Mar 11 11:32:19 EST 2011


2011/3/11 Νικόλαος Κούρας <nikos.kouras at gmail.com>:
> Thanks a lot Steven!
>
> The following code worked like a charm!
>
> ******************
> agent = os.environ['HTTP_USER_AGENT']
>
> # determination of user browser
> agent = agent.lower()
> if 'chrome' in agent:
>        agent = 'Chrome'
> if 'firefox' in agent:
>        agent = 'Firefox'
> if 'opera' in agent:
>        agent = 'Opera'
> if 'safari' in agent:
>        agent = 'Safari'
> if 'msie' in agent:
>        agent = 'IE'
> ***************
>

For compatibility reasons (and because it's also WebKit based), Chrome
also identifies itself as Safari. Just look at the User-Agent string
you posted in the original message:

Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23 (KHTML, like
Gecko) Chrome/11.0.686.0 Safari/534.23



Because of the order of your checks here (and because you're using if
instead of elif), Chrome will be reported as Safari. I suppose you can
fix it for now, but what happens when another browser comes along and
claims to be MSIE-compatible?

Notice that Chrome, like every other browser, introduces itself as
Netscape 5 (Mozilla). After giving you the platform, Chrome correctly
identifies itself as using WebKit as the rendering engine but then
name-drops KHTML (which Webkit was forked from) and Gecko (Firefox's
rendering engine) so that it will get the  version of sites optimized
for those engines (if they haven't identified webkit yet) before
identifying itself as Chrome and then Safari (for the same reason).
Like Steven said, User-Agent strings aren't all that useful for
identifying the browser.

> I just want to have an idea of what browser a guest is using when
> hitting my webpage.
>
> http://www.superhost.gr/?show=log
>
> now includes also that filed in the logging process.
>
> But if i wanted the OS also?
>

I don't think anyone fakes the OS, unless some website is being really
stupid and claims "Windows-only" instead of "IE-only". Just check for
the OS name.



More information about the Python-list mailing list