2026年1月25日星期日

AutoHome Forum Auto Check-In Script Tutorial

This script automates check-ins on AutoHome forum. First, manually log in to export cookies to autohome_cookies.json. Subsequent runs load cookies, visit the forum, automatically find and click check-in/claim buttons, and save screenshots. It includes login verification and retry logic.

1.购买服务器

阿里云:

服务器购买地址

https://t.aliyun.com/U/kcPAeY

若失效,可用地址

https://www.aliyun.com/daily-act/ecs/activity_selection?source=5176.29345612&userCode=49hts92d

腾讯云:

https://curl.qcloud.com/wJpWmSfU

若失效,可用地址

https://cloud.tencent.com/act/cps/redirect?redirect=2446&cps_key=ad201ee2ef3b771157f72ee5464b1fea&from=console

华为云

https://activity.huaweicloud.com/cps.html?fromacct=64b5cf7cc11b4840bb4ed2ea0b2f4468&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905

2.部署教程

2024年最新青龙面板跑脚本教程(一)持续更新中

3.代码如下

# autohome_checkin.py# -*- coding: utf-8 -*-
import jsonimport osimport sysimport timeimport argparsefrom datetime import datetimefrom pathlib import Path
from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout
BASE_URL = "https://club.autohome.com.cn/"COOKIE_FILE = Path("autohome_cookies.json")SCREENSHOT_DIR = Path("screenshots")SCREENSHOT_DIR.mkdir(exist_ok=True)

CHECKIN_KEYWORDS = [    "签到""打卡""每日签到""立即签到""去签到",    "领积分""领取""领取奖励""做任务""任务中心"]
def now_str():    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def log(msg: str):    print(f"[{now_str()}{msg}")
def save_cookies(context, path: Path):    cookies = context.cookies()    path.write_text(json.dumps(cookies, ensure_ascii=False, indent=2), encoding="utf-8")    log(f"✅ Cookie 已保存:{path.resolve()}(共 {len(cookies)} 条)")
def load_cookies(context, path: Path):    if not path.exists():        raise FileNotFoundError(f"未找到 Cookie 文件:{path.resolve()},请先用 --export 手动登录导出一次")    cookies = json.loads(path.read_text(encoding="utf-8"))    context.add_cookies(cookies)    log(f"✅ Cookie 已加载:{path.resolve()}(共 {len(cookies)} 条)")
def screenshot(page, name: str):    p = SCREENSHOT_DIR / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{name}.png"    page.screenshot(path=str(p), full_page=True)    log(f"📸 已截图:{p.resolve()}")
def human_wait(min_s=0.8, max_s=1.6):    # 简单的人类停顿(可按需改为 random)    time.sleep((min_s + max_s) / 2)
def try_click_by_text(page, text: str, timeout_ms=2500) -> bool:    """    优先尝试:根据可见文本点击(适合按钮/链接/菜单)    """    # 常见点击目标:button / a / div(role=button) / span    candidates = [        page.get_by_role("button", name=text),        page.get_by_role("link", name=text),        page.get_by_text(text, exact=False),    ]    for locator in candidates:        try:            if locator.first.is_visible(timeout=timeout_ms):                locator.first.click(timeout=timeout_ms)                return True        except Exception:            continue    return False
def ensure_logged_in(page) -> bool:    """    尝试判断是否登录:页面上通常会出现"退出登录/消息/我的"等入口。    这不是绝对判断,但足够用于自动化流程分支。    """    hints = ["退出登录""我的""消息""个人中心"]    for h in hints:        try:            if page.get_by_text(h, exact=False).first.is_visible(timeout=1500):                return True        except Exception:            pass    return False
def do_checkin(page, max_rounds=3) -> bool:    """    核心签到:循环尝试点击页面中与"签到/打卡/领取"相关的入口    """    for r in range(1, max_rounds + 1):        log(f"🔎 第 {r}/{max_rounds} 轮尝试寻找签到入口…")
        # 先从关键词逐个点击(命中率最高)        clicked_any = False        for kw in CHECKIN_KEYWORDS:            if try_click_by_text(page, kw):                clicked_any = True                log(f"👉 已点击:{kw}")                human_wait()                break
        # 如果没点到,尝试扫一遍页面可点击元素(保守)        if not clicked_any:            log("⚠️ 未直接命中文案按钮,尝试扫描页面链接/按钮进行关键词匹配…")            try:                # 抓取可见的 a/button 文本,做关键词匹配                links = page.locator("a:visible").all()                btns = page.locator("button:visible").all()                nodes = links + btns
                for node in nodes[:300]:  # 限制数量,避免太慢                    try:                        t = (node.inner_text() or "").strip()                        if not t:                            continue                        if any(k in t for k in CHECKIN_KEYWORDS):                            node.click()                            log(f"👉 已点击匹配元素:{t[:30]}")                            clicked_any = True                            human_wait()                            break                    except Exception:                        continue            except Exception as e:                log(f"⚠️ 扫描元素异常:{e}")
        # 如果这轮有点击行为,给页面一点时间加载,然后再检查是否出现"已签到/签到成功"等提示        if clicked_any:            human_wait(1.22.0)
            # 提示关键词            success_hints = ["签到成功""已签到""今日已签到""打卡成功""领取成功""已领取"]            for sh in success_hints:                try:                    if page.get_by_text(sh, exact=False).first.is_visible(timeout=1200):                        log(f"✅ 检测到成功提示:{sh}")                        return True                except Exception:                    pass
            # 如果点击后弹出新窗口/跳转到任务中心,也可能需要继续点一次"签到/领取"            # 所以不中断,让循环继续下一轮        else:            human_wait(0.81.2)
    return False
def export_cookie_flow(headless: bool):    """    手动登录导出 Cookie:    - 打开汽车之家论坛首页    - 手动完成登录(扫码/密码等)    - 回车后保存 cookie    """    with sync_playwright() as p:        browser = p.chromium.launch(headless=headless)        context = browser.new_context()        page = context.new_page()        log(f"🌐 打开:{BASE_URL}")        page.goto(BASE_URL, wait_until="domcontentloaded", timeout=60000)
        log("请在弹出的浏览器中手动完成登录,然后回到终端按回车继续保存 Cookie…")        input()
        # 尝试确认登录        if ensure_logged_in(page):            log("✅ 看起来已登录,准备保存 Cookie")        else:            log("⚠️ 未明显检测到登录态,但仍会保存 Cookie(若后续失败,请重新导出)")
        save_cookies(context, COOKIE_FILE)        screenshot(page, "export_cookie_done")        context.close()        browser.close()
def auto_checkin_flow(headless: bool) -> int:    """    自动签到主流程:    - 加载 cookies    - 访问论坛首页    - 尝试签到    - 截图留证    """    with sync_playwright() as p:        browser = p.chromium.launch(headless=headless)        context = browser.new_context()        load_cookies(context, COOKIE_FILE)
        page = context.new_page()        log(f"🌐 进入:{BASE_URL}")        page.goto(BASE_URL, wait_until="domcontentloaded", timeout=60000)        human_wait()
        if not ensure_logged_in(page):            screenshot(page, "not_logged_in")            log("❌ 可能未登录(Cookie 失效或未正确导入)。请重新运行 --export 导出 Cookie")            return 2
        ok = False        try:            ok = do_checkin(page, max_rounds=3)        except PWTimeout:            log("⚠️ 页面等待超时")        except Exception as e:            log(f"⚠️ 签到过程异常:{e}")
        if ok:            screenshot(page, "checkin_success")            log("🎉 自动签到流程执行完成:疑似成功")            return 0        else:            screenshot(page, "checkin_failed")            log("❌ 自动签到流程执行完成:未检测到成功提示(可能入口变化/风控/需要验证码)")            return 1
def main():    parser = argparse.ArgumentParser(description="汽车之家论坛自动签到(Cookie方式)")    parser.add_argument("--export", action="store_true"help="手动登录并导出 Cookie")    parser.add_argument("--headless", action="store_true"help="无头模式运行(默认有头)")    args = parser.parse_args()
    if args.export:        export_cookie_flow(headless=args.headless)        return 0    else:        return auto_checkin_flow(headless=args.headless)
if __name__ == "__main__":    sys.exit(main())
解析

该脚本为汽车之家自动签到脚本,主要功能包括:

  • 首次人工登录导出 Cookie,把登录态保存到本地文件 autohome_cookies.json

  • 后续自动化运行:加载 Cookie → 打开汽车之家论坛首页 → 自动寻找"签到/打卡/任务中心/领取奖励"等入口并点击 → 判断是否出现"签到成功/已签到"等提示 → 截图留证

主要方法

  • export_cookie_flow() → 打开论坛首页,手动登录后导出并保存 Cookie,便于后续自动签到复用登录态。

  • auto_checkin_flow() → 自动签到主流程:加载 Cookie、打开论坛、判断登录态、执行签到、截图并返回退出码。

  • load_cookies() → 从 autohome_cookies.json 读取 Cookie 并注入浏览器上下文,实现免登录访问。

  • save_cookies() → 将当前浏览器上下文 Cookie 导出到本地文件,保存登录态。

  • ensure_logged_in() → 通过页面关键字(如"退出登录/我的/消息")粗略判断是否处于登录状态。

  • do_checkin() → 自动寻找"签到/打卡/领取"等入口并点击,循环多轮尝试并检测"已签到/签到成功"等提示。

  • try_click_by_text() → 按文本查找可点击元素(按钮/链接/文本),命中则点击,用于提升不同页面结构下的通用性。

  • screenshot() → 失败/成功都截图保存到 screenshots/,方便排查"入口变了/弹验证码/未登录"等问题。

  • human_wait() → 增加固定停顿,模拟正常操作节奏,避免太"机器人"。


注意

本文部分变量已做脱敏处理,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。技术层面需要提供帮助,可以通过打赏的方式进行探讨。


历史脚本txt文件获取>>
服务器搭建,人工服务咨询>>

没有评论:

发表评论

AI全流程开发实践:一周打造桌面智能助手

作者分享仅用一周,全程借助Claude AI完成桌面助手WorkAny开发。从构思到开源发布,AI编写代码、优化架构、处理跨平台打包及用户反馈,实现了高效"vibe coding"体验。 复盘一下我vibe coding 一周,开发 WorkAny 的过程...