做诊断的时候,Search Console 和站长工具给的都是「结果」,日志给的才是「过程」。这份报告我做了三年,现在给客户交付基本靠它。今天把完整做法写出来,代码可以直接跑,改两个路径就能用。
一、先明确要回答的问题
日志能回答的问题,其实只有四类:
- 蜘蛛来了多少、抓了哪些目录、状态码分布如何
- 哪些页面被反复抓、哪些页面从来没被抓过
- 抓取时间分布,是否和内容更新时间错开
- 有没有异常请求(伪造 UA、扫描器、被挂的暗链)
其余的(排名、流量)都别从日志里找,浪费时间。
二、日志格式先统一
Nginx 默认的 combined 格式不够用,建议改成这样:
log_format seo '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $request_time';
关键是加 $request_time,能看出每个请求的响应耗时。没有这个字段,你就不知道蜘蛛抓的是不是慢页面。
改完 reload,新日志从这一刻开始生效,老日志照旧能分析,只是没有耗时字段。
三、解析脚本
import gzip, glob, re, csv, os
from collections import Counter, defaultdict
from datetime import datetime
from urllib.parse import urlparse
LOG_RE = re.compile(
r'(?P<ip>[\d\.]+) - (?P<user>[^ ]*) \[(?P<time>[^\]]+)\] '
r'"(?P<method>[A-Z]+) (?P<url>[^ ]+) [^"]*" (?P<status>\d{3}) '
r'(?P<size>\d+) "[^"]*" "(?P<ua>[^"]*)" (?P<rt>[\d\.\-]+)'
)
BOTS = {
'baiduspider': 'baidu',
'googlebot': 'google',
'bingbot': 'bing',
'360spider': '360',
'sogou': 'sogou',
'yisouspider': 'shenma',
}
def open_log(path):
if path.endswith('.gz'):
return gzip.open(path, 'rt', encoding='utf-8', errors='ignore')
return open(path, encoding='utf-8', errors='ignore')
def parse_line(line):
m = LOG_RE.match(line)
if not m:
return None
d = m.groupdict()
ua = d['ua'].lower()
bot = next((v for k, v in BOTS.items() if k in ua), None)
if not bot:
return None
d['bot'] = bot
d['path'] = urlparse(d['url']).path
try:
d['rt'] = float(d['rt'])
except ValueError:
d['rt'] = -1
return d
解析部分没什么技巧,重点是 BOTS 这张表。常见的六个蜘蛛够了,剩下的小蜘蛛单独统计意义不大。
有个细节:yisouspider 是神马,很多人只统计百度,漏了它。神马在移动端有量,抓取异常往往先体现在它身上。
四、聚合
def analyze(files):
hits = Counter() # 每个路径的抓取次数
status = Counter() # 状态码分布
by_bot = Counter() # 各蜘蛛次数
hourly = defaultdict(Counter) # 每小时各蜘蛛次数
slow = [] # 慢页面
for f in files:
with open_log(f) as fh:
for line in fh:
d = parse_line(line)
if not d:
continue
hits[d['path']] += 1
status[d['status']] += 1
by_bot[d['bot']] += 1
hour = d['time'][13:15]
hourly[hour][d['bot']] += 1
if d['rt'] > 3:
slow.append((d['path'], d['rt'], d['bot']))
return hits, status, by_bot, hourly, slow
hits 是核心。按次数排序,看前 20 名和后 20 名,前 20 是抓取预算的去向,后 20(或者从未出现的)是漏抓的页面。
我的经验:一个 1 万页的站,前 20 个 URL 通常占掉 30%-50% 的抓取量,而这些绝大多数是列表页和 tag 页。
五、算「漏抓」
漏抓需要一份全站 URL 清单,从 sitemap 拿:
import xml.etree.ElementTree as ET
def sitemap_urls(path):
tree = ET.parse(path)
ns = {'s': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
return [u.find('s:loc', ns).text for u in tree.findall('.//s:url', ns)]
def paths_of(urls):
return {urlparse(u).path for u in urls}
然后对比:
all_paths = paths_of(sitemap_urls('sitemap.xml'))
crawled = set(hits.keys())
missing = all_paths - crawled
missing 就是从来没被爬过的页面。这个数如果超过 30%,说明入口结构有问题,先别怪内容。
我们上个客户站 1.2 万页,missing 有 4600 个。查出来是新加的「专题」目录没有从任何地方链进去,只有 sitemap 里有。
六、输出
三张表 + 一个结论:
- 各蜘蛛抓取量、状态码分布
- Top 20 被爬 URL,含次数和目录
- 漏抓 URL 按目录聚合(
/news/ 漏 1200 个,/product/ 漏 300 个……)
按目录聚合这一步很关键。列 4600 条 URL 没人看,按目录归并成 8 行,客户一眼就知道问题在哪。
def group_by_dir(paths, depth=2):
c = Counter()
for p in paths:
parts = p.strip('/').split('/')
c['/' + '/'.join(parts[:depth]) + '/'] += 1
return c
七、定时跑
0 5 * * * cd /opt/logcheck && /usr/bin/python3 report.py --date yesterday >> run.log 2>&1
日志按天切割,脚本跑前一天的。生成 CSV 存到 /opt/logcheck/out/,再同步到自己的看板。
我一般还会在报告里加一行对比:今天的抓取量 vs 上周同一天。掉 50% 以上就值得查。
八、踩过的坑
1. 日志时区
Nginx 的 $time_local 是服务器本地时区,GSC 是 UTC,两边对时间会差 8 小时。我在脚本里统一转成 UTC 再统计,否则「晚上抓取少」这个结论完全是假的。
2. gz 文件乱序
access.log.1.gz 和 access.log.2.gz 是按切割顺序,不是按时间。合并统计的时候要保证文件名排序,或者干脆按 mtime 排。
3. 伪造 UA
有些采集器会带 Baiduspider。判断办法:反查 IP 归属,百度蜘蛛的 IP 段是公开的,脚本里加一个 CIDR 白名单就能过滤掉大部分。
import ipaddress
BAIDU_CIDR = ['220.181.108.0/22', '123.125.71.0/24', '180.76.15.0/24']
def is_real_baidu(ip):
return any(ipaddress.ip_address(ip) in ipaddress.ip_network(c) for c in BAIDU_CIDR)
4. URL 带参数
?from=xxx 会让同一个页面统计成几百条。统计前先丢掉 query,只留 path。要看参数页单独统计。
5. 大文件内存
一年的日志几百 G,别一次读进内存。按文件流式处理,或者用 ClickHouse / DuckDB。DuckDB 读 parquet 很快,值得一试。
九、这套东西的价值
说个具体的:一个客户坚持认为「内容是问题」,收录上不去。跑完报告发现详情页平均抓取间隔 11 天,而列表页每天被抓 40 次。问题明显在结构,不在内容。改完内链和分页,三周后详情页抓取涨了 3 倍。
日志不会说谎,它只是需要你把它整理成能看的样子。