Question

What is the best method to parse a User-Agent string in Python to reliably detect

  1. Browser
  2. Browser version
  3. OS

Or perhaps any helper library that does it

Was it helpful?

Solution

Answering my own question ;)

Finally I decided to go by suggestion#1 i.e. write your own. And I am happy with the outcome. Please feel free to use/modify/send me patch etc.

It's here -> http://pypi.python.org/pypi/httpagentparser

OTHER TIPS

UASparser for Python by Hicro Kee. Auto updated datafile and cache from remote server with version checking.

Werkzeug has user-agent parsing built-in.

New link (Jun 2018) http://werkzeug.pocoo.org/docs/0.14/utils/#module-werkzeug.useragents

Having run these suggestions against the full corpus of Firefox User Agents, I've found that the version-number parsing for comparison is quite poor.

If that's what you need, I suggest that you take a look at UAparser, which used to be part of the browserscope project. Documentation here.

The other responses to this question are rather old now. I believe the new standard in Browser User Agent parsing is Browserscope's user agent parser.

Also conveniently available with the exact same matching patterns in many other languages. Someday you might want to also parse some UA strings in JavaScript and you don't need to worry about inconsistent parsing.

Th Browser Cap Parser should work. It may be a bit slow though..

However if you wish to parse all this on the Python side you can use the XML/INI files provided at http://browsers.garykeith.com/downloads.asp to do lookups on the user agent. This is the same file that is used in php's get_browser() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top