Web上のHTMLからPython Notebookを自動生成してみた


初めに

GitHubのREADME記載のExampleとかをNotebookで実行したことがちまちまあります。
数が多いとコピペも面倒ですし、何よりそんな生産性ゼロなことに時間を奪われたくない!!
ということでBeautifulSoupjupytextで自動化してみました。
皆さんの貴重な時間を節約するために是非ご活用くださいー!

実装

GithubのREADMEの場合はelementdivclass_highlight-source-pythonを指定すればPythonのコードブロックのみをとってこれます。その他のWebページでもパラメータをよしなに変更していただければ動くかと。

import requests
from bs4 import BeautifulSoup
import jupytext

def convert_html_to_ipynb(
    url: str,
    filename: str,
    element: str = "div",
    class_: str = "highlight-source-python",
) -> None:
    """Fetch HTML and extract only its code block and save it as ipynb."""
    res = requests.get(URL)
    soup = BeautifulSoup(res.text, "html.parser")
    py_percent_text = "\n# %%\n".join(
        [x.get_text() for x in soup.find_all(element, class_=class_)]
    )
    nb_text = jupytext.reads(py_percent_text, fmt="py")
    jupytext.write(nb_text, filename)

convert_html_to_ipynb("https://github.com/...", 'sample.ipynb')

終わりに

このコードで皆さんの1秒が節約できれば幸いです。