Grabbing user's agent and OS type

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Mar 11 10:04:03 EST 2011


On Fri, 11 Mar 2011 06:37:42 -0800, Νικόλαος Κούρας wrote:

> Hello,
> 
> I use
> 
> os.environ["HTTP_USER_AGENT"] and is very convenient to retrieve the
> user's agent type
> 
> but how could we also retrieve the user's OS type?

>>> sys.platform
'linux2'
>>> os.name
'posix'

 
> OS type and agent type and version do appear in the same string. I
> somehow have to grab the 'OS' type(Windows) and the user's agent/
> version(Chrome 11)
> 
> 
> The string is:
> [code]
> Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/534.23 (KHTML, like
> Gecko) Chrome/11.0.686.0 Safari/534.23 [/code]
>
> How am i supposed to filter the string since the subsparts of the string
> isn't always the same and maybe also in different positions within the
> each time different returned string?

useragent = "Mozilla/5.0 blah blah blah"
agent = useragent.lower()
if "mozilla" in agent:
    print "user-agent claims to be Mozilla compatible"
if "chrome" in agent:
    print "user-agent claims to be Chrome compatible"
if "safari" in agent:
    print "user-agent claims to be Safari compatible"
if "python" in agent:
    print "user-agent claims to be a Python program, module or script"
if "lynx" in agent:
    print "user-agent claims to be the Lynx browser"
if "links" in agent:
    print "user-agent claims to be the Links browser"
if "windows" in agent:
    print "user-agent claims that the operating system is Windows"
# and so on
print "remember that user-agents can, and frequently do, lie"


I think you give the user-agent string too much credit. Despite what some 
people think, including some browser developers, it's a free-form string 
and can contain anything the browser wants. There's no guarantee that 
fields will appear in a particular order, or even appear at all. If 
you're doing feature detection by parsing the UA string, you're in a 
state of sin.



-- 
Steven



More information about the Python-list mailing list