​user_agents提供了一个简单的方法来判断用户设备(手机、平板..)和使用什么类型的浏览器。它是基于ua-parser的。​

 

安装:



 




1




pip install pyyaml ua-parser user-agents



使用:



 




1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26


27


28


29


30


31


32


33




>>> from user_agents import parse


>>> ua_string = 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'


>>> # 浏览器属性


>>> user_agent = parse(ua_string)


>>> user_agent.browser


Browser(family=u'Mobile Safari', version=(5, 1), version_string='5.1')


>>> user_agent.browser.family


u'Mobile Safari'


>>> user_agent.browser.version


(5, 1)


>>> user_agent.browser.version_string


'5.1'


>>> # 操作系统属性


>>> user_agent.os


OperatingSystem(family=u'iOS', version=(5, 1), version_string='5.1')


>>> user_agent.os.family


u'iOS'


>>> user_agent.os.version


(5, 1)


>>> user_agent.os.version_string


'5.1'


>>> # 设备属性


>>> user_agent.device


Device(family=u'iPhone', brand=u'Apple', model=u'iPhone')


>>> user_agent.device.family


u'iPhone'


>>> user_agent.device.brand


u'Apple'


>>> user_agent.device.model


u'iPhone'


>>>


>>> str(user_agent)


'iPhone / iOS 5.1 / Mobile Safari 5.1'



它还提供了属性判断:

  • is_mobile:判断是不是手机
  • is_tablet:判断是不是平板
  • is_pc:判断是不是桌面系统
  • is_touch_capable:有没有触屏功能
  • is_bot:是不是搜索引擎的爬虫

例如:



 




1


2


3


4


5


6


7


8


9


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24


25


26


27


28


29


30


31


32




>>> # 古老的黑莓手机


>>> ua_string = 'BlackBerry9700/5.0.0.862 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/331 UNTRUSTED/1.0 3gpp-gba'


>>> user_agent = parse(ua_string)


>>> user_agent.is_mobile


True


>>> user_agent.is_tablet


False


>>> user_agent.is_touch_capable


False


>>> user_agent.is_pc


False


>>> user_agent.is_bot


False


>>> str(user_agent)


'BlackBerry 9700 / BlackBerry OS 5 / BlackBerry 9700'


>>>


>>> # android 手机


>>> ua_string = 'Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'


>>> user_agent = parse(ua_string)


>>> user_agent.is_mobile


True


>>> user_agent.is_tablet


False


>>> user_agent.is_touch_capable


True


>>> user_agent.is_pc


False


>>> user_agent.is_bot


False


>>> str(user_agent)


'Samsung GT-I9300 / Android 4.0.4 / Android 4.0.4'


>>>



 


技术链接