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

时间:2013-09-03 08:43:16

标签: python regex split

我想从用户代理字符串中提取其版本的botname。我尝试使用分割功能。但是,由于显示用户代理字符串的方式不同,从一个爬虫到另一个爬虫,获得预期输出的最佳方法是什么?(请考虑我需要一般解决方案)

输入(用户代理字符串)

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

1 个答案:

答案 0 :(得分:2)

请尝试以下操作:

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

假设机器人代理名称包含bot/

相关问题