LoginSignup
3
5

More than 3 years have passed since last update.

Webブラウザでhtml文字列を開く

Last updated at Posted at 2019-06-14

(この記事を書いた時の環境:macOS Mojave 10.14.4 & Python 3.7.3)

Pythonにはwebbrowserという標準ライブラリがある。

以下のようにurlを渡してやることでそのurlをウェブブラウザで開いてくれる。

>>> import webbrowser
>>> url = "https://www.google.co.jp"
>>> webbrowser.open_new_tab(url)   #新しいタブで開く

"file:///"を付けて渡してあげればローカルファイルも開ける。

>>> import webbrowser
>>> url = "file:///Users/hoge/Documents/hello.html"
>>> webbrowser.open_new_tab(url)   #新しいタブで開く

ファイルパスやurlじゃなくてhtml文字列から開きたい

でもwebbrowser自体はurl(やファイルパス)をWebブラウザで開く機能しかない。

しゃーなし一時ファイルを作ってそのパスをwebbrowserに渡そう。

web_opener.py
import webbrowser
import tempfile
import time
html = "<!doctype html>\n<html>\n<head>\n<title>Hello world!</title>\n</head>\n<body>\nHello world!\n</body>\n</html>"
with tempfile.NamedTemporaryFile("w+", suffix=".html") as fp: #名前付きの一時ファイル作成
    fp.write(html) #書き込み
    fp.seek(0) #先頭に戻す
    webbrowser.open_new_tab("file://"+fp.name)  #新しいタブで開く
    time.sleep(1) #一秒待つ

webbrowserはブラウザを開く命令を投げるだけで、Webブラウザのロード完了を待ってくれない。
そのため少し待たないとWebブラウザでロードが完了する前に一時ファイルが消える。
そのため、html文字列のサイズや環境によっては、もっと削除までのsleepが必要かもしれません。

htmlをpython上でいじってそのままWebブラウザで表示を確認したいときに便利。 
(だけどもっといい方法があるような気がしなくもない。今後思い付いたら記事にする予定。)

以上。

3
5
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
3
5