快榜GEO|用 Python 批量检测站点的 AI 就绪度:六项检查加一个能跑的脚本

一句话:单个站点的 AI 就绪度可以手工查,几十个站点就得靠脚本。这篇给一份能跑的批量检测工具。

先说场景。

手上有十几个客户站点,每个都要查 robots.txt 有没有封 AI 爬虫、页面是不是服务端渲染、有没有 JSON-LD、meta robots 是不是 index。一项项手工点,一天就没了。

写个脚本批量跑,几分钟出结果。这篇把脚本和判断逻辑都给出来。

一、检测哪几项

先定清楚要查什么。对 AI 可见度影响最大的,抽出来六项:

  1. robots.txt 是否放行 AI 爬虫——检查检索型 UA 有没有被 Disallow
  2. 页面是否服务端渲染——初始 HTML 里有没有正文
  3. meta robots 是否为 noindex——页面级索引开关
  4. 是否有 JSON-LD 结构化数据——实体信息能不能被机器读
  5. 是否有 canonical 标签——避免多版本 URL 分散
  6. Sitemap 是否可访问——页面发现入口

这六项都不是充分条件,但都是必要条件。有一项出问题,AI 就可能读不到或者读错。

二、完整脚本

用 requests + BeautifulSoup,装依赖:

pip install requests beautifulsoup4

脚本主体:

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
import json
import time

# 检索型 AI 爬虫:这些被封等于退出 AI 搜索
SEARCH_BOTS = [
    "OAI-SearchBot",
    "ChatGPT-User",
    "PerplexityBot",
    "Claude-SearchBot",
    "Baiduspider",
    "Bytespider",
    "PetalBot",
    "YisouSpider",
]

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
}


def check_robots(base):
    """检查 robots.txt 是否封了检索型 AI 爬虫"""
    url = urljoin(base, "/robots.txt")
    try:
        r = requests.get(url, headers=HEADERS, timeout=10)
        if r.status_code != 200:
            return {"ok": None, "detail": f"robots.txt 返回 {r.status_code}"}
        text = r.text.lower()
        blocked = []
        for bot in SEARCH_BOTS:
            # 简单匹配:UA 名后面跟 Disallow
            for line in text.splitlines():
                line = line.strip()
                if line.startswith("#") or ":" not in line:
                    continue
                ua, _, rule = line.partition(":")
                if bot.lower() in ua.lower() and "disallow" in rule.lower():
                    blocked.append(bot)
                    break
        if blocked:
            return {"ok": False, "detail": "封了: " + ", ".join(blocked)}
        return {"ok": True, "detail": "检索型爬虫未被封"}
    except Exception as e:
        return {"ok": None, "detail": f"请求失败: {e}"}


def parse_page(base):
    try:
        r = requests.get(base, headers=HEADERS, timeout=15)
        r.raise_for_status()
        return r
    except Exception as e:
        return None


def check_render(soup, html):
    """判断初始 HTML 里有没有足够正文"""
    for tag in soup(["script", "style", "nav", "footer"]):
        tag.decompose()
    text = soup.get_text(strip=True)
    return {
        "ok": len(text) >= 300,
        "detail": f"初始 HTML 正文 {len(text)} 字符"
    }


def check_meta_robots(soup):
    tag = soup.find("meta", attrs={"name": lambda v: v and v.lower() == "robots"})
    if not tag:
        return {"ok": True, "detail": "未设置(默认 index)"}
    content = (tag.get("content") or "").lower()
    if "noindex" in content or "none" in content:
        return {"ok": False, "detail": f"meta robots={content}"}
    return {"ok": True, "detail": f"meta robots={content}"}


def check_jsonld(soup):
    tags = soup.find_all("script", attrs={"type": "application/ld+json"})
    if not tags:
        return {"ok": False, "detail": "无 JSON-LD"}
    types = []
    for t in tags:
        try:
            data = json.loads(t.string or "{}")
            items = data if isinstance(data, list) else [data]
            for item in items:
                if isinstance(item, dict) and "@graph" in item:
                    items.extend(item["@graph"])
                if isinstance(item, dict) and item.get("@type"):
                    types.append(str(item["@type"]))
        except Exception:
            pass
    return {"ok": True, "detail": f"{len(tags)} 段,类型: {', '.join(types[:5]) or '解析失败'}"}


def check_canonical(soup, base):
    tag = soup.find("link", attrs={"rel": "canonical"})
    if not tag or not tag.get("href"):
        return {"ok": False, "detail": "无 canonical"}
    href = tag["href"]
    ok = href.startswith("http") and urlparse(href).netloc == urlparse(base).netloc
    return {"ok": ok, "detail": href}


def check_sitemap(base):
    url = urljoin(base, "/sitemap.xml")
    try:
        r = requests.get(url, headers=HEADERS, timeout=10, allow_redirects=False)
        return {
            "ok": r.status_code == 200,
            "detail": f"返回 {r.status_code},{len(r.content)} 字节"
        }
    except Exception as e:
        return {"ok": None, "detail": f"请求失败: {e}"}


def audit(base):
    if not base.startswith("http"):
        base = "https://" + base
    print(f"\n检查 {base}")
    results = {"url": base}

    results["robots"] = check_robots(base)

    resp = parse_page(base)
    if not resp:
        results["page"] = {"ok": False, "detail": "首页无法访问"}
        for k in ["render", "meta", "jsonld", "canonical", "sitemap"]:
            results[k] = {"ok": None, "detail": "跳过"}
        return results

    soup = BeautifulSoup(resp.text, "html.parser")
    results["render"] = check_render(soup, resp.text)
    results["meta"] = check_meta_robots(soup)
    results["jsonld"] = check_jsonld(soup)
    results["canonical"] = check_canonical(soup, base)
    results["sitemap"] = check_sitemap(base)

    for k, v in results.items():
        if k == "url":
            continue
        mark = {True: "OK", False: "FAIL", None: "SKIP"}[v["ok"]]
        print(f"  [{mark}] {k}: {v['detail']}")
    return results


if __name__ == "__main__":
    sites = [
        "https://www.example1.com",
        "https://www.example2.com",
    ]
    reports = [audit(s) for s in sites]

    with open("audit_report.json", "w", encoding="utf-8") as f:
        json.dump(reports, f, ensure_ascii=False, indent=2)
    print("\n报告已保存到 audit_report.json")

三、几个实现细节

为什么 robots.txt 用简单文本匹配,不用 robotparser?

Python 标准库的 urllib.robotparser 对 UA 匹配的实现比较老旧,对 OAI-SearchBot 这类新式 UA 支持不好。批量筛查用文本匹配更直接,先把明显封了的找出来。

要精确判断,可以再用 robotparser 复核一遍。

为什么正文长度阈值是 300?

纯前端渲染的页面,初始 HTML 里通常只有 <div id="app"></div>,正文字符数接近 0。服务端渲染的页面,光导航和页脚就可能几百字符。300 是个经验值,能分出大部分情况,误判了可以自己调。

为什么 JSON-LD 要把 @graph 展开?

很多站把多个实体放在一个 @graph 数组里。不展开的话只能读到一个 @type,看不出实际有哪些实体。

四、批量跑的注意事项

别并发太猛。 对一组站同时发几十个请求,容易被当成攻击。串行跑,每个站之间加个间隔:

import time
reports = []
for site in sites:
    reports.append(audit(site))
    time.sleep(1)

超时要设。 有些站响应很慢,不设 timeout 脚本会卡死。上面脚本都设了 10-15 秒。

结果落盘。 几十个站跑下来输出很长,直接写 JSON 文件,后面用 Excel 或者脚本再分析。

只检测首页不够。 首页通常是做得最好的页面,内页才是问题集中区。真要做全面体检,每个站至少抽首页、产品页、文章页三类。把 sites 换成 URL 列表就行。

五、怎么读结果

OK 的项不用管,FAIL 的按优先级处理:

  1. robots FAIL:最高优先级,AI 连门都进不来
  2. meta FAIL:noindex 让页面白抓
  3. render FAIL:正文是 JS 渲染的,爬虫看到空白
  4. jsonld FAIL:缺结构化数据,实体信息不好读
  5. canonical FAIL:多版本 URL 分散权重
  6. sitemap FAIL:页面发现入口缺失

前三项是"能不能被读",后三项是"读懂了能不能认对"。顺序别反。

SKIP 表示首页都访问不了,先解决访问问题。

小结

批量检测的价值不在脚本本身,在于把"凭感觉优化"变成"逐项打分"。

六项里任何一项 FAIL,都能定位到具体环节,改完再跑一遍就能看到变化。这比笼统地说"我们做了 AI 优化"有用得多。

脚本给的是基础版,实际用的时候按自己的站点结构加检测项——比如加 hreflang、加 og 标签、加特定行业的结构化数据类型。框架是现成的,加项很容易。


以上数据来源:快榜GEO(www.fasthot.cn)公开的实践记录。文中代码可直接复制修改后使用。

posted @ 2026-12-01 12:18  Android开发团队  阅读(3)  评论(0)    收藏  举报