【Python】Chromeブラウザのブックマークをweblocファイルでエクスポートしてみた

chrome ブラウザで使用するブックマーク。

バックアップ用にエクスポートする時に、html形式などにすることができるが、

そのぞれのURLを webloc ファイル形式 (Macのブラウザ用ショートカット)に、したくなった。

そこで、Python でプログラムしてみた。

# coding:utf-8

import json
import os
import shutil
import textwrap

BOOKMARK_PATH = "【アウトプット用フォルダパス】"

class Txt:

    def txt(text_path: str,val):
        print(val)

        Txt.writeTxt(text_path,val)

    def clearTxt(text_path: str):

        f = open(text_path, 'w', encoding='UTF-8')
        f.truncate(0)
        f.close()

    def writeTxt(text_path: str,log: str):

        f = open(text_path, 'a', encoding='UTF-8')
        f.write(log + '\n')
        f.close()

def get_items(arr, parent):

    for d in arr:
        if d["type"] == "folder":
            parent_dir = parent + "/" + str(d["name"]).replace("/", "|") + "/"
            if os.path.isdir(parent_dir) is False:
                os.mkdir(parent_dir)

            get_items(d["children"], parent_dir)

        if d["type"] == "url":
            create_webloc(str(d["name"]).replace("/", "|"), d["url"], parent)

def create_webloc(name, url, parent):
    global BOOKMARK_PATH

    txt = textwrap.dedent('''
        <?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
    <key>URL</key>
    <string>{url}</string>
</dict>
</plist>
        ''').format(name=name, url=url).strip()

    webloc_file = parent + name + ".webloc"

    Txt.clearTxt(webloc_file)
    Txt.txt(webloc_file, txt)

def main():
    global BOOKMARK_PATH

    if os.path.exists(BOOKMARK_PATH):
        shutil.rmtree(BOOKMARK_PATH)
    os.mkdir(BOOKMARK_PATH)

    path1 = "/【ユーザーID】/Library/Application Support/Google/Chrome/Default/Bookmarks"

    f = open(path1, 'r')
    json_dict = json.load(f)

    bookmark_list = json_dict["roots"]["bookmark_bar"]["children"]
    get_items(bookmark_list, BOOKMARK_PATH)

main()

ブックマークのツリー構造をそのままに、フォルダをツリー構造にして書き出す仕組み。