从用户代理字符串Python中提取机器人程序名称



我想从用户代理字符串中提取botname及其版本。我试过使用split函数。但是,由于显示用户代理字符串的方式不同于不同的爬网程序,那么获得预期输出的最佳方式是什么?(请考虑我需要一个通用的解决方案)

输入(用户代理字符串)

Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)
msnbot/2.0b (+http://search.msn.com/msnbot.htm)

预期输出

Googlebot/2.1
AhrefsBot/4.0
msnbot/2.0b

尝试以下操作:

import re
lines = [
    'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
    'Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)',
    'msnbot/2.0b (+http://search.msn.com/msnbot.htm)'
]
botname = re.compile('w+bot/[.w]+', flags=re.IGNORECASE)
for line in lines:
    matched = botname.search(line)
    if matched:
        print(matched.group())

打印

Googlebot/2.1
AhrefsBot/4.0
msnbot/2.0b

假设机器人程序代理名称包含CCD_ 1。

最新更新