Sitemap lastmod 精度优化与自动更新脚本
Sitemap 中的 `lastmod` 字段告诉 AI 爬虫某个页面最近一次修改的时间。AI 引擎利用这个字段判断是否需要重新抓取页面。`lastmod` 精度不足会导致爬虫频繁抓取未变化的页面,或者漏抓已更新的页面。
精度的影响
lastmod 的精度分为三个层级:
精度层级 | 格式 | AI 爬虫行为 |
日期级 | `2026-07-18` | 爬虫无法判断页面的具体修改时间,在同一天内无法区分先后 |
时间级 | `2026-07-18T10:00:00+08:00` | 爬虫能够识别当天的多次修改,准确度高 |
秒级(推荐) | `2026-07-18T10:00:00+08:00` | 秒级精度,覆盖 Git 或 CI/CD 的精确更新时间戳 |
大部分 AI 爬虫对 lastmod 精度的最低要求是时间级。日期级 lastmod 的存在意味着爬虫只能以"天"为单位判断更新。
自动更新脚本实现
以下 Node.js 脚本读取文件系统的修改时间,更新到 Sitemap 的 lastmod 字段中:
const fs = require('fs'); const path = require('path'); const SITEMAP_PATH = './public/sitemap.xml'; const PAGES_DIR = './pages'; // 页面文件目录 // 获取文件的 Git 最后修改时间 function getGitLastModified(filePath) { const { execSync } = require('child_process'); try { const result = execSync( `git log -1 --format="%cI" -- "${filePath}"`, { encoding: 'utf-8', timeout: 5000 } ); return result.trim(); } catch { // 如果 Git 不可用,回退到文件系统 mtime const stats = fs.statSync(filePath); return stats.mtime.toISOString(); } } // 读取当前 Sitemap let sitemap = fs.readFileSync(SITEMAP_PATH, 'utf-8'); // 提取所有 URL 条目 const urlRegex = /<url>([\s\S]*?)<\/url>/g; let match; let updated = false; while ((match = urlRegex.exec(sitemap)) !== null) { const urlBlock = match[1]; const locMatch = urlBlock.match(/<loc>(.*?)<\/loc>/); if (!locMatch) continue; const pagePath = locMatch[1].replace('https://yourdomain.com/', ''); const sourceFile = path.join(PAGES_DIR, pagePath.replace(/\/$/, '/index'), 'index.html'); if (fs.existsSync(sourceFile)) { const lastmod = getGitLastModified(sourceFile); const oldLastmod = urlBlock.match(/<lastmod>(.*?)<\/lastmod>/); if (oldLastmod && oldLastmod[1] !== lastmod) { sitemap = sitemap.replace(oldLastmod[1], lastmod); updated = true; } } } if (updated) { fs.writeFileSync(SITEMAP_PATH, sitemap, 'utf-8'); console.log('Sitemap lastmod 已更新'); } else { console.log('无需更新'); }
部署到 CI/CD 流水线
在 GitHub Actions 或 GitLab CI 中,将脚本放在构建流程的最后一步:
# .github/workflows/deploy.yml 片段 - name: Update Sitemap lastmod run: node scripts/update-lastmod.js - name: Deploy run: npm run deploy
每次推送代码时,脚本会自动检查所有源文件的 Git 最后修改时间,对比 Sitemap 中的 lastmod,只在有变更时更新文件。
验证 lastmod 是否生效
# 查看 Sitemap 中的 lastmod 值 curl -s https://yourdomain.com/sitemap.xml | grep '<lastmod>' # 提交给 Google curl "https://www.google.com/ping?sitemap=https://yourdomain.com/sitemap.xml"
提交 Sitemap 后,AI 爬虫会在下一次爬取周期中读取更新后的 lastmod 值。不需要额外通知 DeepSeek 或 Claude 等 AI 引擎,它们会定期检查已收录站点的 Sitemap。
*参考:[致君GEO](https://zhijunai.com) 技术博客*