如何从 Python 在浏览器中打开 HTML 文件?

新手上路,请多包涵

我正在尝试从 Python 打开一个 HTML 文件,但我的脚本只是在 Python 中显示 HTML 文件的内容,而不是在浏览器中打开它。我该如何解决这个问题?如何在我的 Chrome 浏览器中打开 HTML 文件?

测试数据.html

 <div>
    <a href="https://plot.ly/user001/2/" target="_blank" title="Success vs Failure" style="display: block; text-align: center;"><img src="https://plot.ly/~user001/2.png" alt="Success vs Failure" style="max-width: 100%;width: 600px;"  width="600" onerror="this.onerror=null;this.src='https://plot.ly/404.png';" /></a>
    <script data-plotly="user001:2"  src="https://plot.ly/embed.js" async></script>
</div>

Python 2.7 脚本:

 import urllib
page =  urllib.urlopen('testdata.html').read()
print page

原文由 user7135817 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

尝试在 URL 的开头指定“file://”。

 // Also, use the absolute path of the file:

webbrowser.open('file://' + os.path.realpath(filename))

要么

import webbrowser
new = 2 # open in a new tab, if possible

// open a public URL, in this case, the webbrowser docs
url = "http://docs.python.org/library/webbrowser.html"
webbrowser.open(url,new=new)

// open an HTML file on my own (Windows) computer
url = "file://d/testdata.html"
webbrowser.open(url,new=new)

原文由 user3146115 发布,翻译遵循 CC BY-SA 3.0 许可协议

import os
os.system("start [your's_url]")

享受!

原文由 Yuval Pruss 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题