原文:http://blog.topspeedsnail.com/archives/1958
Python3網絡爬蟲(四):使用User Agent和代理IP隱藏身份-------https://blog.csdn.net/c406495762/article/details/60137956
python3 網絡爬蟲(五)scrapy中使用User-Agent-----------------https://blog.csdn.net/Fight_Huang/article/details/76650972
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'
>>>
|