一个非常神奇的包可以帮助我们优雅的解析浏览器的UA,他的名字叫做user_agents
pip install pyyaml ua-parser user-agents
>>>
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'
批量解析:采用apply函数
- data['user_agent'] = data['ua'].apply(lambda x:parse(x))