Pythonのrequestsを利用してWebページをhtmlファイルに保存

表題の件、利用するたびに毎回調べているので、メモしておく。

https://meganedesu.com/というWebページの内容(html)をout.htmlというファイルに保存するコードは以下のとおり。

import requests

url = "https://meganedesu.com/"

out_path = "out.html"

try:
    response = requests.get(url)
    response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)

    # Determine encoding (if not already determined)
    if response.encoding is None:
        response.encoding = response.apparent_encoding

    content = response.text

    # Save the content to a file
    with open(out_path, "w", encoding=response.encoding) as f:
        f.write(content)

    print(f"Successfully saved content to {out_path}")

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

urlを変更しした場合は、urlという変数を、保存したいファイルのパスを変更した場合は、out_pathをそれぞれ変更すればよい。

上記を実行して保存されたhtmlファイルをJupyter Notebook上で閲覧した様子が以下のスクリーンショット

無事に本ブログの内容がhtmlファイルに保存されていることが確認できる。以上。