【问题标题】:Extract bot name from user-agent string-Python从用户代理字符串中提取机器人名称-Python
【发布时间】:2013-09-06 10:04:27
【问题描述】:

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

输入(用户代理字符串)

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

【问题讨论】:

标签: python regex split


【解决方案1】:

尝试以下操作:

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/

【讨论】:

  • 感谢 falsetru!...:) 这正是我所期望的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 2022-12-14
  • 1970-01-01
  • 2013-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多