1
0
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

レガシーなWEBサイトの大量のファイルにGTMのタグを自動で追加したい

Last updated at Posted at 2024-01-29

目的

大量のHTML、PHPファイルで構成されたWEBサイトにGoogleタグマネージャーを一括でインストールしたい。

経緯

htmlやPHPで構成されたレガシーなWEBサイトに大量のファイルが。
それらのファイルにはヘッダーやフッターなどの共通部分がモジュール化されておらず。
その為、googleタグマネージャーなどの全ページに設定したタグは一つずつ職人の手で手作業で更新する必要が。
地道に数十ファイルを更新した結果、気が滅入ってきたので、どうにか一括で更新するべく一念発起。

成果物

指定したフォルダ内の指定した拡張子のファイルの中から、指定した文字列を含むファイルに対して置き換え処理をするシンプルなものができました。
同じ文字を置き換えするファイルが大量にある場合に有効。

import os

# ファイルの中に指定した文字列を含むか確認
def check_string(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        datafile = file.readlines()
    for line in datafile:
        if "更新対象となるファイルに含まれる文字列" in line:
            return True
    return False

# 指定した文字列を指定した箇所に追加
def replace_tag(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    # 置き換え対象
    replace_tag = """<head>
<script>
"""
    # 置き換える文字
    set_tag = """<head>
<!-- Google Tag Manager -->
<script>
</script>
<!-- End Google Tag Manager -->
<script>
"""

    
    replaced_content = content.replace(replace_tag, set_tag)

    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(replaced_content)

def del_tag(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 削除するタグ
    # 古いタグなど
    del_tag = """<!-- Google tag (gtag.js) -->
</script>
"""

    
    replaced_content = content.replace(del_tag, '')

    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(replaced_content)

def replace_files(dir_path):
    
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if file.endswith('.html') or file.endswith('.php'):
                file_path = os.path.join(root, file)
                    
                if check_string(file_path):
                    # タグを削除
                    # GA4のタグをGTMに置き換えたいなど。
                    # コメントアウト
                    #del_tag(file_path)

                    # タグを追加
                    replace_tag(file_path)

                    print(f'更新完了: {file_path}')
                
                

if __name__ == "__main__":
    # 更新したいファイルが存在するディレクトリのパスを指定
    target_dir = '対象ディレクトリを指定'
    
    replace_files(target_dir)

解説

フォルダの中にあるファイルを走査

def replace_files(dir_path):
    
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            if file.endswith('.html') or file.endswith('.php'):
                file_path = os.path.join(root, file)
                    
                if check_string(file_path):
                    # タグを追加
                    replace_tag(file_path)

                    # タグを削除
                    del_tag(file_path)
                    
                    print(f'更新完了: {file_path}')
for root, dirs, files in os.walk(dir_path):

os.walkの戻り値
・ディレクトリ名:String:root
・内包するディレクトリ一覧:list:dirs
・内包するファイル一覧:list:files

for file in files:

ファイル一覧を順番に処理

if file.endswith('.html') or file.endswith('.php'):

ファイル名の末尾(拡張子)がhtmlかphpが対象

file_path = os.path.join(root, file)

os.path.joinでパスを結合してファイルパスを取得

if check_string(file_path):

ファイルの中に指定した文字列がある場合にTRUE

replace_tag(file_path)

ファイルの中を指定した文字を指定した文字に置き換え

with open(file_path, 'r', encoding='utf-8') as file:
    content = file.read()

ファイルの中身を読み込み。
(withブロックを使うとブロックの終了時に自動的にクローズされ、close()が不要になる。)

replaced_content = content.replace(replace_tag, set_tag)

文字列の置き換え。replace_tagをset_tagに置き換え。

with open(file_path, 'w', encoding='utf-8') as file:
    file.write(replaced_content)

ファイル書き込み。

注意

一括で置き換えてしまうので、置き換え後の文字が置き換え前に合致すると2回、3回と処理を繰り返すと同じ箇所に繰り返し処理が実行されてしまうので注意。
置き換え後は置き換え前に合致しないように。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0