首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >用 nginx 访问日志统计各家搜索引擎和 AI 爬虫到底抓了什么(附 Python 脚本)

用 nginx 访问日志统计各家搜索引擎和 AI 爬虫到底抓了什么(附 Python 脚本)

原创
作者头像
用户10896297
发布于 2026-11-30 11:51:19
发布于 2026-11-30 11:51:19
50
举报

为什么要看日志

站长平台能告诉你“收录了多少”,但回答不了三个更前面的问题:

  1. 这家爬虫最近来过没有?
  2. 来了抓的是哪些页面,是不是只看了首页?
  3. 返回的状态码对不对,有没有大量 4xx、5xx?

而 GPTBot、ClaudeBot、Bytespider 这类 AI 爬虫根本没有站长平台。要回答这些问题,最直接的数据就在 nginx 访问日志里。

数据源和一个坑

nginx 默认的 combined 日志格式是:

代码语言:txt
复制
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"

里面没有域名($host)。 如果一台机器上多个站点共用同一个 access.log,你分不清这一行属于哪个站。我们的服务器就是这样:官网、后台和几个托管站写在同一个文件里。

两种处理办法:

  • 推荐:给要统计的站点单独配一个日志,或在 log_format 里加上 $host;
  • 我们暂时用的办法:只把“这个站独有的路径”(产品页、文章页、案例、指南等)算作该站的抓取,/、/robots.txt、/sitemap.xml 这类各站都有的路径单独列为“共有路径”。

识别爬虫

按 UA 关键词归类,顺序有意义,先匹配更具体的:

归类

UA 关键词

百度

Baiduspider

必应

bingbot、BingPreview、msnbot

360

360Spider、HaosouSpider

搜狗

Sogou web spider 等

神马

YisouSpider

字节(头条/豆包)

Bytespider

Google

Googlebot、Google-InspectionTool、GoogleOther

OpenAI

GPTBot、OAI-SearchBot、ChatGPT-User

Anthropic

ClaudeBot、Claude-User、Claude-SearchBot

Perplexity

PerplexityBot、Perplexity-User

华为

PetalBot

UA 可以伪造。对百度、必应、Google 这类公布了验证方法的爬虫,可以做“反查 + 正查”:先用 IP 反查主机名,确认后缀(如 .baidu.com、.search.msn.com、.googlebot.com),再把主机名正查回 IP,确认一致。

核心代码

完整脚本只用 Python 标准库,下面是主要部分:

代码语言:python
复制
import datetime as dt, gzip, os, re, socket, collections

LINE = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)[^"]*" (\d{3}) \S+ "[^"]*" "([^"]*)"')
CRAWLERS = [
    ('百度', re.compile(r'Baiduspider', re.I), ('.baidu.com', '.baidu.jp')),
    ('必应', re.compile(r'bingbot|BingPreview|msnbot', re.I), ('.search.msn.com',)),
    ('Google', re.compile(r'Googlebot|Google-InspectionTool|GoogleOther', re.I), ('.googlebot.com', '.google.com')),
    ('字节(头条/豆包)', re.compile(r'Bytespider', re.I), None),
    ('OpenAI', re.compile(r'GPTBot|OAI-SearchBot|ChatGPT-User', re.I), None),
    # ……其余见上表
]
# 预筛:区分大小写的子串判断,比忽略大小写的正则快得多
KEYS = ('bot', 'Bot', 'spider', 'Spider', 'BOT', 'crawler', 'BingPreview', 'ChatGPT', 'Claude', 'Perplexity', 'Sogou', 'Yisou')

def open_log(path):
    return gzip.open(path, 'rt', errors='replace') if path.endswith('.gz') else open(path, errors='replace')

def verified(ip, suffixes):
    try:
        host = socket.gethostbyaddr(ip)[0].lower()
        return host.endswith(suffixes) and ip in socket.gethostbyname_ex(host)[2]
    except OSError:
        return False

def scan(files, since):
    stats = collections.defaultdict(lambda: {'n': 0, 'status': collections.Counter(), 'paths': collections.Counter(), 'ips': set()})
    for path in files:
        # 轮转后的旧文件最后修改时间早于统计起点,里面不可能有窗口内的记录,直接跳过
        if dt.datetime.fromtimestamp(os.path.getmtime(path), dt.timezone.utc) < since:
            continue
        with open_log(path) as f:
            for line in f:
                if not any(k in line for k in KEYS):
                    continue
                m = LINE.match(line)
                if not m:
                    continue
                ip, stamp, _, target, status, ua = m.groups()
                name = next((n for n, p, _ in CRAWLERS if p.search(ua)), None)
                if not name or dt.datetime.strptime(stamp, '%d/%b/%Y:%H:%M:%S %z') < since:
                    continue
                s = stats[name]
                s['n'] += 1
                s['status'][status[0] + 'xx'] += 1
                s['paths'][target.split('?', 1)[0]] += 1
                s['ips'].add(ip)
    return stats

再加上:把路径按“本站独有 / 共有 / 其他”分类;从线上 sitemap 读出网址清单,算出每家爬虫抓到了 sitemap 里的多少条;--verify-dns 时每家最多抽 20 个 IP 做反查。

性能:从 5 分钟到 15 秒

第一版用忽略大小写的正则 re.compile(r'bot|spider|crawler|…', re.I) 预筛每一行,并且每个轮转文件都打开读一遍。统计 7 天(当前日志加若干个 .gz 轮转文件)用了 5 分 12 秒,CPU 基本跑满。

做了两处改动:

  1. 预筛改成区分大小写的子串判断 any(k in line for k in KEYS);
  2. 按文件修改时间跳过早于统计窗口的轮转文件。

同样命中 2,515 行、结果一致,耗时降到 约 15 秒。(两处改动是一起上的,没有分别计时。)

实际结果

这是我们官网(上线约两个月、sitemap 里 71 个公开网址)最近 7 天的数据:

爬虫

抓本站页面次数

不同网址数

sitemap 71 条中抓到

备注

必应

93

47

44

抓得最充分

Google

60

38

24

华为 Petal

37

31

32

Anthropic

27

27

27

百度

10

7

8

首页另抓了 48 次

搜狗

3

1

2

神马

3

1

2

字节

3

1

1

主要抓 sitemap 和 robots

OpenAI

3

1

2

主要抓 robots 和 sitemap

360

0

0

1

只抓首页和 robots

DNS 反查:百度 20/20、必应 20/20 个 IP 确认来源;Google 20 个里确认 11 个,其余没有反查到 .googlebot.com 或 .google.com 后缀,原因没有逐个追查;字节的 15 个 IP 反查后缀都不是我们设的 .bytedance.com,只能说明这条规则对它不适用,不能据此认定是伪造。

几个结论:

  • 国内引擎里只有必应在正常抓取,百度、360、搜狗、神马、头条几乎只看首页。站长平台里“索引量低”的原因,在日志里一眼就能看出来:根本没抓到内页。
  • 对这类新站,等爬虫自己发现内页太慢,要主动推送:百度 API 推送、头条与搜狗的链接提交、必应的 IndexNow。
  • 推送之后再跑一次脚本,就能看到推送有没有带来实际抓取。

小结

站长平台给结果,日志给过程。一个只读日志、不碰业务数据的小脚本,每周跑一次,就能看到每家搜索引擎和 AI 爬虫有没有来、抓了什么、抓得对不对。


作者:客来(QELAI)技术团队。我们在做官网的搜索引擎与 AI 收录时用到了这个脚本,欢迎交流。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 为什么要看日志
  • 数据源和一个坑
  • 识别爬虫
  • 核心代码
  • 性能:从 5 分钟到 15 秒
  • 实际结果
  • 小结
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档