#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""fix_heshan_retry3.py —— 只给 search_api 的 requests.get 加重试"""
import ast, os, shutil, subprocess, time
D = "/root/gov_crawler/"; f = "crawl_heshan_gkmlpt.py"; p = D + f
src = open(p, encoding="utf-8").read()
OLD = '    r = requests.get(url, params=params, headers=HEADERS, timeout=30)\n'
NEW = ('    r = None\n'
       '    for _try in range(3):        # QC20260926 重试：search_api 原先裸奔，源站偶发失败会崩整轮\n'
       '        try:\n'
       '            r = requests.get(url, params=params, headers=HEADERS, timeout=30)\n'
       '            break\n'
       '        except Exception:\n'
       '            if _try == 2:\n'
       '                raise\n'
       '            time.sleep(3 * (_try + 1))\n')
n = src.count(OLD)
print("锚点命中:", n)
if n != 1: raise SystemExit("锚点不唯一，放弃")
new = src.replace(OLD, NEW, 1)
try: ast.parse(new)
except SyntaxError as e: raise SystemExit("语法错（未落盘）: %s" % e)
print("语法 ✅")
b = D + "Archive/" + f + ".bak_20260926_retry3"
if not os.path.exists(b): shutil.copy2(p, b)
open(p, "w", encoding="utf-8").write(new)
print("✅ 已落盘（备份 %s）" % os.path.basename(b))
print("time 已导入:", "import time" in src)
t0 = time.time()
try:
    r = subprocess.run(["python3", p, "龙口镇"], capture_output=True, text=True, timeout=115, cwd=D)
    print("EXIT=%d 耗时=%.0fs" % (r.returncode, time.time() - t0))
    for x in [y for y in (r.stdout or "").split("\n") if y.strip()][:5]:
        print("   out:", x[:100])
    errs = [y for y in (r.stderr or "").split("\n") if y.strip()][-2:]
    for x in errs: print("   ERR:", x[:100])
except subprocess.TimeoutExpired:
    print("⏱ >115s（在正常爬，属预期）")
