Parsing HTTP User-Agent string

2019-01-10 22:03发布

问题:

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

回答1:

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



回答2:

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



回答3:

Werkzeug has user-agent parsing built-in.

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



回答4:

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.



回答5:

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.

  • UA Parser pypi package
  • UA Parser on github

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.



回答6:

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



回答7:

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.