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

标签 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

最佳答案

尝试在 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)

关于python - 如何从 Python 在浏览器中打开 HTML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40905703/

相关文章:

python - 在不复制代码的情况下访问函数中声明的所有变量

python - 加密的 Django 模型字段

python - 将 Google App Engine 与 flask 和 flask-restplus 一起使用时出现 404 错误

python - 扩展 Python 队列的正确方法?

python - 使用Python检测短网址

HTML 和 CSS : Place Checkbox in Top Right of an Image

javascript - 带图像的输入类型按钮

Jquery 动态创建可拖动的 div

html - 无序列表在第 3 项后进入新列

html - Tumblr 静态页面,删除内联 CSS