V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xkwdm
V2EX  ›  Python

[ Python ] 批量把代码加入到 head 元素里面。

  •  
  •   xkwdm · 10 天前 · 819 次点击

    日常需要把谷歌跟踪代码加入到 head 元素里面,所以借助 AI 写了一个小工具。

    1 、把需要加入的内容保存到 GACode.txt 文件中

    2 、执行代码,输入目录即可。(只会修改 html 扩展名的文件)

    代码

    import os
    import re
    import sys
    from pathlib import Path
    
    def get_resource_path(relative_path):
        """获取资源文件的绝对路径,支持 PyInstaller 打包"""
        try:
            # PyInstaller 创建临时文件夹,并将路径存储在_MEIPASS 中
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)
    
    def check_and_add_google_analytics():
        """
        检查所有 HTML 文件是否包含 Google Analytics 代码,如果不存在则添加
        """
        # 初始化统计信息
        stats = {
            'total': 0,
            'modified': 0,
            'skipped': 0,
            'errors': 0
        }
       
        # 从 GACode.txt 文件读取 Google Analytics 代码
        ga_code_file = get_resource_path('GACode.txt')
       
        try:
            with open(ga_code_file, 'r', encoding='utf-8') as f:
                ga_code = f.read().strip()
        except FileNotFoundError:
            print(f"错误:找不到文件 {ga_code_file}")
            stats['errors'] = 1
            return stats
        except Exception as e:
            print(f"错误:读取 GA 代码文件时出错: {str(e)}")
            stats['errors'] = 1
            return stats
       
        if not ga_code:
            print("错误:GA 代码文件为空")
            stats['errors'] = 1
            return stats
       
        # 获取当前目录下所有 HTML 文件
        html_files = list(Path('.').glob('*.html'))
        stats['total'] = len(html_files)
       
        print(f"找到 {len(html_files)} 个 HTML 文件")
       
        for html_file in html_files:
            print(f"\n 处理文件: {html_file}")
            
            try:
                # 读取文件内容
                with open(html_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # 检查是否已经包含 Google Analytics 代码
                if 'googletagmanager.com/gtag/js' in content:
                    print(f"  ✓ {html_file} 已包含 Google Analytics 代码,跳过")
                    stats['skipped'] += 1
                    continue
                
                # 查找</head>标签的位置
                head_end_pattern = r'</head>'
                match = re.search(head_end_pattern, content, re.IGNORECASE)
                
                if not match:
                    print(f"  ✗ {html_file} 未找到</head>标签,跳过")
                    stats['errors'] += 1
                    continue
                
                # 在</head>标签前插入 Google Analytics 代码
                head_end_pos = match.start()
                new_content = (
                    content[:head_end_pos] +
                    '    ' + ga_code + '\n' +
                    content[head_end_pos:]
                )
                
                # 写入修改后的内容
                with open(html_file, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                
                print(f"  ✓ {html_file} 已成功添加 Google Analytics 代码")
                stats['modified'] += 1
                
            except Exception as e:
                print(f"  ✗ 处理 {html_file} 时出错: {str(e)}")
                stats['errors'] += 1
       
        print("\n 处理完成!")
        return stats
    
    if __name__ == "__main__":
        try:
            # 获取用户输入的目录路径
            current_dir = input("请输入要处理的目录路径: ").strip()
            
            # 如果用户没有输入,则使用当前目录
            if not current_dir:
                current_dir = os.getcwd()
            
            print(f"当前工作目录: {current_dir}")
            
            # 切换到指定目录
            try:
                os.chdir(current_dir)
            except FileNotFoundError:
                print(f"错误:目录 '{current_dir}' 不存在")
                input("\n 按回车键退出...")
                exit(1)
            except PermissionError:
                print(f"错误:没有权限访问目录 '{current_dir}'")
                input("\n 按回车键退出...")
                exit(1)
            
            # 检查是否在包含 HTML 文件的目录中
            html_files = list(Path('.').glob('*.html'))
            if not html_files:
                print("当前目录下没有找到 HTML 文件,请确保在正确的目录下运行此脚本")
                input("\n 按回车键退出...")
                exit(1)
            
            # 执行添加 Google Analytics 代码的操作
            stats = check_and_add_google_analytics()
            
            # 检查返回值是否有效
            if stats is None:
                print("\n⚠ 函数执行异常,无法获取统计信息")
                stats = {'total': 0, 'modified': 0, 'skipped': 0, 'errors': 1}
            
            # 显示统计结果
            print("\n=== 执行统计 ===")
            print(f"总文件数: {stats['total']}")
            print(f"成功修改: {stats['modified']} 个")
            print(f"已存在跳过: {stats['skipped']} 个")
            print(f"处理失败: {stats['errors']} 个")
            
            if stats['modified'] > 0:
                print(f"\n✓ 成功为 {stats['modified']} 个 HTML 文件添加了 Google Analytics 代码!")
            elif stats['total'] > 0 and stats['skipped'] == stats['total']:
                print("\n✓ 所有 HTML 文件都已包含 Google Analytics 代码,无需修改。")
            else:
                print("\n⚠ 没有成功修改任何文件,请检查文件格式或权限。")
            
            print("\n=== 程序执行完成 ===")
            input("\n 按回车键退出...")
            
        except KeyboardInterrupt:
            print("\n\n 程序被用户中断")
            input("\n 按回车键退出...")
        except Exception as e:
            print(f"\n 程序执行时发生未知错误: {str(e)}")
            input("\n 按回车键退出...")
    

    我就不发成品了,自行打包哈

    4 条回复    2025-08-07 18:14:02 +08:00
    irisdev
        1
    irisdev  
       10 天前
    不懂 python ,不过这个输入目录是不是没用,ga_code_file = get_resource_path('GACode.txt')
    xkwdm
        2
    xkwdm  
    OP
       10 天前
    @irisdev 输入目录是 html 文件的所在目录,ga_code_file = get_resource_path('GACode.txt') 这一段是读取这个 python 文件的所在目录里面的 GACode.txt 文件。
    irisdev
        3
    irisdev  
       10 天前
    @irisdev get
    rcchen123
        4
    rcchen123  
       7 天前
    好巧。
    我也是用 AI 写了一段代码,给指定路径下的 html 添加页头、页脚、head 。
    方便只编辑一次,批量替换、批量实现更新。
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1130 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 18:12 · PVG 02:12 · LAX 11:12 · JFK 14:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.