踩坑实录:Ahrefs Session 持久化
踩坑实录:Ahrefs Session 持久化
我的 Ahrefs 自动化脚本,每隔 7 天就断~
因为 Ahrefs 的 session 7 天过期,Playwright 保存的 cookie 失效了。
自动化最怕的就是「需要人工介入」
问题描述
我用 Playwright 登录 Ahrefs,保存了 storage state:
// 登录一次
await page.goto('https://app.ahrefs.com');
// ... 登录操作 ...
await page.context().storageState({ path: '.ahrefs_state.json' });
下次直接用:
const context = await browser.newContext({
storageState: '.ahrefs_state.json'
});
问题:7 天后 cookie 过期,脚本返回登录页面。
解决方案 1:定期刷新
写个 cron job,每 5 天刷新一次 session:
# 每 5 天 0 点刷新
0 0 */5 * * node /scripts/ahrefs_refresh.js
刷新脚本:
// 用现有 session 打开页面
const context = await browser.newContext({
storageState: '.ahrefs_state.json'
});
const page = await context.newPage();
await page.goto('https://app.ahrefs.com/dashboard');
// 检查是否还在登录态
const isLoggedIn = await page.locator('.user-menu').count() > 0;
if (!isLoggedIn) {
// 发通知,需要手动登录
await sendAlert('Ahrefs session expired, need manual login');
} else {
// 刷新 cookie
await page.context().storageState({ path: '.ahrefs_state.json' });
}
解决方案 2:检测 + 自动恢复
在主脚本里加检测:
const page = await context.newPage();
await page.goto('https://app.ahrefs.com/keywords-explorer');
// 检测是否被重定向到登录页
if (page.url().includes('/login')) {
// 自动恢复:发通知
await sendAlert('Ahrefs session expired');
// 退出,等人工处理
process.exit(1);
}
关键:不要在脚本里自动登录,因为 Ahrefs 有 MFA(邮箱验证码)。
解决方案 3:用 3ue.com 代理
3ue.com 提供了 Semrush/Ahrefs 的代理 API,不需要自己维护 session。
curl https://dash.3ue.com/api/keywords \
-H "Authorization: Bearer xxx" \
-d "keyword=openclaw"
缺点是要付费,但省了维护 session 的麻烦。
教训
任何需要登录的自动化,都要考虑 session 过期
方案选择:
- 短期项目:手动登录 + 存储 session
- 长期项目:用代理 API(3ue.com)
- 免费方案:定期刷新 + 人工兜底
你的自动化脚本,多久需要人工介入一次~