#!/usr/bin/env python3
"""给 html_table_to_html 函数体加 BeautifulSoup 导入（处理 as BS 局部导入的情况）"""
import os, ast

DIR = '/root/gov_crawler'
TARGETS = ['crawl_linli_hp.py', 'crawl_kdl_sthj.py']

OLD = 'def html_table_to_html(table, base_url=""):\n    """保留 HTML 表格结构，仅将相对链接/图片转绝对 URL"""\n    tbl = BeautifulSoup(str(table), \'html.parser\')'
NEW = 'def html_table_to_html(table, base_url=""):\n    """保留 HTML 表格结构，仅将相对链接/图片转绝对 URL"""\n    from bs4 import BeautifulSoup\n    tbl = BeautifulSoup(str(table), \'html.parser\')'

for name in TARGETS:
    path = os.path.join(DIR, name)
    s = open(path).read()
    if OLD in s:
        s = s.replace(OLD, NEW)
        try:
            ast.parse(s)
            open(path, 'w').write(s)
            print(f"FIXED {name}")
        except Exception as e:
            print(f"FAIL {name}: {e}")
    else:
        # 检查是否已修复
        print(f"CHECK {name}: {'from bs4 import BeautifulSoup' in s}")
