WordPressの記事を一括PDF化
ソースを限定して活用できるNotebook LMが便利ですね。
ガイドラインや法文などのPDFをソースとして読み込ませて活用していますが、HPだと一括でソースとして活用できないのが不便です。
そこで、Wordpress(管理者限定)の記事を一括でPDF化するPythonを作成しました。
と言っても自力でコードを書いたわけではなく、Geminiを使って調整しながら書いてもらいました。
事前準備
WordPressの管理画面から「ツール」→「エクスポート」を使用しXMLファイルとして書き出します。
このままだと、テキストは確認できますが、画像はリンク先だったり余計なヘッダーやフッターなどの「ノイズ」が文字として読み取られてしまい、AIが混乱する原因になります。
Pythonコードの作成
下記のコードテキストエディタなどに貼り付
けて、 「convert.py」という名前で保存します。
日本語に対応するため、保存の時、メモ帳などで「文字コード」(またはエンコード)を 「UTF-8」 に変更します。
Pythonコード-----------下記をコピーしてテキストエディタに貼り付け
import os
import re
# --- SETTINGS ---
xml_file = 'WordPress.xml'
output_file = 'archive_catalog.html'
def run():
print("--- STARTING ROBUST PROCESS ---")
if not os.path.exists(xml_file):
print(f"ERROR: '{xml_file}' not found.")
return
# HTML Header
html_data = '<html><head><meta charset="UTF-8"><style>'
html_data += 'body{font-family:sans-serif;max-width:800px;margin:20px auto;line-height:1.6;background:#f9f9f9;}'
html_data += 'article{background:white;padding:30px;margin-bottom:20px;border:1px solid #ddd;border-radius:8px;}'
html_data += 'h2{color:#d35400;border-bottom:2px solid #d35400;}'
html_data += 'img{max-width:100%;height:auto;display:block;margin:20px auto;}'
html_data += '.date{color:#888;font-size:0.8em;}'
html_data += '</style></head><body><h1>Archive Data (Robust Mode)</h1>'
count = 0
try:
# Open file as plain text, ignore encoding errors
with open(xml_file, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
# Split by <item> tag
items = content.split('<item>')
print(f"Found {len(items)} raw blocks. Extracting...")
for item in items[1:]: # Skip the first block before the first <item>
# Use Regex to find Title, Date, and Content
title_match = re.search(r'<title>(.*?)</title>', item, re.DOTALL)
date_match = re.search(r'<wp:post_date>(.*?)</wp:post_date>', item, re.DOTALL)
content_match = re.search(r'<content:encoded><!\[CDATA\[(.*?)]]></content:encoded>', item, re.DOTALL)
if title_match and content_match:
title = title_match.group(1)
date = date_match.group(1) if date_match else "Unknown"
body = content_match.group(1)
# Append to HTML
html_data += f"<article><h2>{title}</h2><div class='date'>Date: {date}</div><hr>{body}</article>"
count += 1
if count % 50 == 0:
print(f" Processed {count} posts...")
html_data += "</body></html>"
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html_data)
print(f"SUCCESS: {count} posts saved to '{output_file}'!")
except Exception as e:
print(f"SYSTEM ERROR: {e}")
if __name__ == "__main__":
run()
print("--- PROCESS FINISHED ---")
input("Press Enter to close this window...")
---------------------ここまで
実行方法
1.PCにPythonが入っていればOK(追加ライブラリのインストールは不要)。
2.「convert.py」の5行目の WordPress.xml を、Wordpressでエクスポートしたファイル名に書き換えてください。
3.「convert.py」とエクスポートした XMLファイルを同じフォルダに入れる。
4.convert.pyのダブルクリックで実行する。
上記でうまく実行できない場合、フォルダの上の「アドレスバー」をクリックして、cmd と入力してEnterを押すと、その場所でコマンドプロンプトが開くので、py convert.py と入力し実行する。
5.同じフォルダに archive_catalog.html が出来上がります。
6.PDFにプリントアウトすれば完成
本HPのエコ・コラムを一括HTMLしたのが下の画像



