从零开始手把手教企业技术团队使用Playwright开发AI搜索引擎自动化检测脚本,覆盖环境搭建、多平台适配、反爬虫策略、结果采集与分析的完整开发流程。
Playwright是微软开源的浏览器自动化框架,相比Selenium具有更快的执行速度、更好的稳定性和原生支持多浏览器的能力。对于AI搜索检测场景,Playwright的headless模式和拦截网络请求的能力尤为关键。
环境要求:Python 3.10+、Playwright Python包、Chromium浏览器引擎。建议在Linux服务器上运行以获得最佳稳定性和成本效率,Windows开发环境也完全支持。
安装步骤:使用pip安装playwright包,然后执行playwright install chromium安装浏览器引擎。如果需要在CI/CD环境中运行,建议使用playwright install --with-deps chromium一次性安装所有系统依赖。
Python >= 3.10(推荐3.12)
playwright >= 1.40.0
Chromium引擎自动随playwright install安装
建议使用虚拟环境隔离依赖
# 环境安装命令
# pip install playwright
# playwright install chromium
# 验证安装
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.goto('https://example.com')
print(f'Page title: {page.title()}')
browser.close()
print('Playwright environment ready!')一个好的AI搜索检测脚本需要支持多个AI平台,每个平台的页面结构、交互方式和回答渲染机制都不同。因此脚本架构应采用策略模式(Strategy Pattern),为每个AI平台实现独立的检测器类,统一接口便于扩展。
核心架构组件包括:PlatformDetector基类(定义统一接口)、各平台具体检测器(ChatGPTDetector、PerplexityDetector、KimiDetector等)、关键词管理器(管理待检测关键词列表)、结果采集器(收集和格式化检测结果)、调度器(协调各组件执行流程)。
设计原则:每个平台检测器独立工作互不影响,某个平台检测失败不影响其他平台;检测结果统一格式化输出(JSON结构),包含平台名称、关键词、AI回答全文、品牌提及状态、情感倾向、引用链接等信息;支持断点续跑,已检测的关键词跳过。
# 多平台检测脚本架构
class PlatformDetector:
'''AI平台检测器基类'''
def __init__(self, headless=True):
self.headless = headless
self.platform_name = 'base'
def detect(self, page, keyword, brand_name):
'''执行检测,返回结果字典'''
raise NotImplementedError
def _check_mention(self, text, brand_name):
'''检查品牌是否被提及'''
return brand_name.lower() in text.lower()
class ChatGPTDetector(PlatformDetector):
def __init__(self, headless=True):
super().__init__(headless)
self.platform_name = 'chatgpt'
self.url = 'https://chatgpt.com'
def detect(self, page, keyword, brand_name):
page.goto(self.url)
page.wait_for_selector('textarea', timeout=15000)
page.fill('textarea', keyword)
page.press('textarea', 'Enter')
# 等待AI回答完成
page.wait_for_selector('[data-testid="final-message"]', timeout=60000)
response_text = page.text_content('[data-testid="final-message"]')
return {
'platform': self.platform_name,
'keyword': keyword,
'response': response_text,
'brand_mentioned': self._check_mention(response_text, brand_name),
'timestamp': page.evaluate('Date.now()')
}
class KimiDetector(PlatformDetector):
def __init__(self, headless=True):
super().__init__(headless)
self.platform_name = 'kimi'
self.url = 'https://kimi.moonshot.cn'
def detect(self, page, keyword, brand_name):
page.goto(self.url)
page.wait_for_selector('.chat-input', timeout=15000)
page.fill('.chat-input', keyword)
page.click('.send-button')
page.wait_for_selector('.response-content', timeout=60000)
response_text = page.text_content('.response-content')
return {
'platform': self.platform_name,
'keyword': keyword,
'response': response_text,
'brand_mentioned': self._check_mention(response_text, brand_name),
'timestamp': page.evaluate('Date.now()')
}AI搜索平台普遍部署了反自动化检测机制,包括Cloudflare人机验证、行为指纹检测、频率限制等。脚本需要采取多层策略来保障稳定运行。
反检测核心策略:使用stealth模式隐藏自动化特征(注入stealth.min.js隐藏navigator.webdriver等属性)、模拟人类操作节奏(随机延迟3-8秒、模拟鼠标移动轨迹)、使用真实浏览器User-Agent、保持Cookie和Session持久化(避免每次登录)、合理控制请求频率(每个平台每小时不超过20次查询)。
稳定性保障措施:实现自动重试机制(单次检测失败自动重试3次,间隔递增)、网络异常捕获与日志记录、截图保存(检测失败时自动截图便于排查)、代理IP轮换(高频检测场景下使用住宅代理IP池)、浏览器实例定期重启(每检测50个关键词后重启浏览器释放内存)。
遵守各AI平台的服务条款,部分平台禁止自动化访问
控制查询频率,避免对平台造成负担
仅用于品牌自身的AI搜索可见度监测,不用于竞品间谍活动
建议优先使用平台官方API(如OpenAI API),仅在API不提供搜索功能时使用浏览器自动化
# 反检测与稳定性保障实现
import random
import time
from playwright.sync_api import sync_playwright
# Stealth模式配置
STEALTH_JS = '''
// 隐藏webdriver标志
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
// 模拟真实浏览器插件
Object.defineProperty(navigator, 'plugins', {
get: () => [1, 2, 3, 4, 5]
});
// 模拟真实语言
Object.defineProperty(navigator, 'languages', {
get: () => ['zh-CN', 'zh', 'en']
});
'''
def create_stealth_browser(playwright, headless=True):
browser = playwright.chromium.launch(
headless=headless,
args=[
'--disable-blink-features=AutomationControlled',
'--no-sandbox',
'--disable-dev-shm-usage'
]
)
context = browser.new_context(
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
viewport={'width': 1920, 'height': 1080},
locale='zh-CN'
)
context.add_init_script(STEALTH_JS)
return browser, context
def human_delay(min_sec=3, max_sec=8):
'''模拟人类操作延迟'''
time.sleep(random.uniform(min_sec, max_sec))
def retry_with_backoff(func, max_retries=3):
'''带退避的重试机制'''
for attempt in range(max_retries):
try:
return func()
except Exception as e:
wait = (attempt + 1) * 10
print(f'Attempt {attempt+1} failed: {e}, retry in {wait}s')
time.sleep(wait)
raise Exception(f'Failed after {max_retries} retries')检测脚本的核心产出是结构化的结果数据。每个关键词在每个平台的检测结果应包含:平台名称、关键词、AI回答全文、品牌提及布尔值、品牌首次出现位置、回答中的所有链接列表、检测时间戳。
结果存储建议使用JSON Lines格式(每行一个JSON对象),便于流式处理和追加写入。对于大规模检测(100+关键词×5平台),建议使用SQLite数据库存储,支持高效查询和聚合分析。
分析流程:首先统计各平台的品牌提及率(提及次数/检测次数),然后分析品牌提及的上下文(使用LLM API进行情感分析),最后生成可视化报告(提及率趋势图、平台对比柱状图、关键词热力图)。
| 分析维度 | 计算方法 | 输出格式 | 决策价值 |
|---|---|---|---|
| 品牌提及率 | 提及次数/总检测次数 | 百分比 | 评估整体可见度 |
| 首次出现位置 | 品牌名在回答中的字符位置 | 前1/3/中1/3/后1/3 | 评估推荐优先级 |
| 情感倾向 | LLM分析提及上下文 | 正面/中性/负面 | 评估品牌声誉 |
| 链接引用率 | 包含品牌链接的回答比例 | 百分比 | 评估流量获取能力 |
| 竞品共存率 | 同一回答中竞品也出现的比例 | 百分比 | 评估竞争态势 |
AI搜索检测脚本需要定期执行以追踪效果变化。推荐使用cron(Linux)或Task Scheduler(Windows)进行定时调度,也可以集成到GitHub Actions或Airflow中实现更复杂的调度逻辑。
调度频率建议:核心关键词(10-20个)每日检测一次,完整关键词矩阵(50-100个)每周检测一次。频率过高不仅增加服务器成本,还可能触发AI平台的频率限制。
执行流程:调度器启动脚本→加载关键词列表→初始化浏览器→逐平台逐关键词执行检测→保存结果到数据库/JSON文件→生成当日检测摘要→发送通知到Slack/邮件。整个流程应支持中断恢复,避免因单次失败导致全部重跑。
# 定时调度配置 (Linux crontab)
# 每天早上8点执行核心关键词检测
# 0 8 * * * cd /opt/geo-detector && python -X utf8 run_detection.py --mode=daily
# 每周一早上8点执行全量关键词检测
# 0 8 * * 1 cd /opt/geo-detector && python -X utf8 run_detection.py --mode=weekly
# run_detection.py 核心调度逻辑
import argparse
import json
from datetime import datetime
def run_detection(mode='daily'):
config = json.load(open('config.json', 'r', encoding='utf-8'))
if mode == 'daily':
keywords = config['core_keywords'] # 10-20个核心词
else:
keywords = config['all_keywords'] # 50-100个全量词
results = []
for kw in keywords:
for platform in config['platforms']:
try:
result = detect_keyword(kw, platform, config['brand_name'])
results.append(result)
print(f'OK: {platform} | {kw}')
except Exception as e:
print(f'FAIL: {platform} | {kw} | {e}')
results.append({'keyword': kw, 'platform': platform, 'error': str(e)})
# 保存结果
output_file = f'results/detection_{datetime.now().strftime("%Y%m%d_%H%M%S")}.jsonl'
with open(output_file, 'w', encoding='utf-8') as f:
for r in results:
f.write(json.dumps(r, ensure_ascii=False) + '\n')
# 生成摘要
total = len(results)
mentioned = sum(1 for r in results if r.get('brand_mentioned'))
print(f'\nDetection complete: {mentioned}/{total} mentioned ({mentioned/total:.1%})')
print(f'Results saved to: {output_file}')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--mode', default='daily', choices=['daily', 'weekly'])
args = parser.parse_args()
run_detection(args.mode)基础检测脚本搭建完成后,可以根据业务需求扩展高级功能。推荐的高级功能包括:多账号轮换检测(使用不同账号避免单账号频率限制)、回答内容变更追踪(同一关键词不同时间的AI回答差异分析)、AI回答截图归档(保存每次检测的页面截图作为证据)、多语言检测(支持中英文双语关键词的跨语言品牌可见度追踪)。
脚本维护要点:AI平台的页面结构会不定期更新,导致CSS选择器失效。建议在脚本中实现选择器自愈机制——当主选择器失效时自动尝试备选选择器。同时建立检测成功率监控,当成功率低于80%时自动告警通知开发人员更新选择器。
性能优化建议:使用异步模式(Playwright async API)并行检测多个关键词、使用浏览器上下文池复用浏览器实例、对AI回答文本进行增量提取(等待回答完成后一次性提取,避免频繁DOM查询)。
Phase 1(1-2周):基础检测脚本+单平台验证
Phase 2(2-3周):多平台支持+定时调度+结果存储
Phase 3(3-4周):反检测优化+LLM情感分析+可视化报告
Phase 4(持续):选择器自愈+多账号轮换+性能优化