LoginSignup
0
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2022-03-28

初めに

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秒が節約できれば幸いです。

0
0
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
0
0