2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Chromeの履歴をSQLで取得して、そのHTMLをMarkItDownでテキストにして集約する

Posted at

概要

Chromeを使って検索した内容を一つのテキストの集約して生成AIに渡したい。
Chromeの履歴をSQLで取得して、そのHTMLをMarkItDownでテキストにして集約するコードを作成した。
今回のコードはWindowsで動作する。

Chromeの履歴取得について

Chromeの履歴情報が格納されているHistoryファイルは、SQLを使うことで履歴を検索することができる。
Windows以外など環境が異なる場合は、Historyファイルの場所を確かめて使ってほしい。

今回のコードでできること

履歴取得数limitを編集して実行すると
image.png

Chromeの履歴の一覧と
image.png

そのURLの内容をひとつのテキストにまとめる。
image.png

動機

  • Chromeの履歴を生成AIに与えて質問することで、記事を思い出したり、複数の記事をまとめた

ソースコード(Pythonファイル)

import os
import shutil
import sqlite3
from pathlib import Path
from markitdown import MarkItDown

# ==============================
# 1. Chrome 履歴のX件を取得
# ==============================

def get_chrome_history(limit=100):
    history_path = Path(os.getenv("LOCALAPPDATA")) / r"Google\Chrome\User Data\Default\History"

    temp_history = Path("history_copy.db")
    shutil.copy2(history_path, temp_history)

    conn = sqlite3.connect(temp_history)
    cursor = conn.cursor()

    query = f"""
    SELECT
        url,
        title,
        datetime((last_visit_time/1000000)-11644473600, 'unixepoch', 'localtime') AS last_visit
    FROM urls
    ORDER BY last_visit_time DESC
    LIMIT {limit};
    """

    cursor.execute(query)
    rows = cursor.fetchall()
    cursor.close()
    conn.close()

    temp_history.unlink()

    return rows


# ==============================
# 2. URL の内容を Markdown に変換
# ==============================

def url_to_markdown(url):
    try:
        result = MarkItDown().convert(url)
        return result.markdown
    except Exception as e:
        return f"---\n【取得失敗】{url}\nError: {str(e)}\n---\n"


# ==============================
# 3. すべてを history.md に書き込む
# ==============================

def save_all_to_markdown(limit=100):
    rows = get_chrome_history(limit)

    with open("history.md", "w", encoding="utf-8") as f:

        f.write("# Chrome History (Markdown Converted)\n\n")

        # -----------------------------
        # ★ まず URL とタイトルの一覧を作成
        # -----------------------------
        f.write("## URL List\n\n")
        for idx, (url, title, last_visit) in enumerate(rows, start=1):
            title = title if title else "(No Title)"
            f.write(f"{idx}. [{title}]({url})  \n")
        f.write("\n\n---\n\n")

        # -----------------------------
        # ★ 詳細(Markdown コンテンツ)
        # -----------------------------
        for idx, (url, title, last_visit) in enumerate(rows, start=1):
            title = title if title else "(No Title)"
            f.write(f"\n\n---\n")
            f.write(f"## {idx}. {title}\n")
            f.write(f"- URL: {url}\n")
            f.write(f"- Last Visit: {last_visit}\n\n")

            f.write("### ▼ Markdown Content\n\n")

            md = url_to_markdown(url)
            f.write(md)
            f.write("\n\n")

    print("history.md を作成しました。")


# ==============================
# 編集箇所
# ==============================
if __name__ == "__main__":
    save_all_to_markdown(limit=5)
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?