如何从 Python 在浏览器中打开 HTML 文件? [英] How to open an HTML file in the browser from Python?

查看:200
本文介绍了如何从 Python 在浏览器中打开 HTML 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

testdata.html

<a href="https://plot.ly/user001/2/" target="_blank" title="成功与失败" style="display: block; text-align: center;"><imgsrc="https://plot.ly/~user001/2.png" alt="成功与失败" 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>

Python 2.7 脚本:

导入urllibpage = urllib.urlopen('testdata.html').read()打印页面

解决方案

尝试在 URL 的开头指定file://".

//另外,使用文件的绝对路径:webbrowser.open('file://' + os.path.realpath(filename))

导入浏览器new = 2 # 如果可能,在新标签页中打开//打开一个公共 URL,在本例中为 webbrowser 文档url = "http://docs.python.org/library/webbrowser.html"webbrowser.open(url,new=new)//在我自己的 (Windows) 计算机上打开一个 HTML 文件url = "file://d/testdata.html"webbrowser.open(url,new=new)

I am trying to open an HTML file from Python but my script just displays the contents of the HTML file in Python instead of opening it in the browser. How can I fix this problem? How can I open the HTML file in my Chrome browser?

testdata.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 script:

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

解决方案

Try specifying the "file://" at the start of the URL.

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

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

Or

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 在浏览器中打开 HTML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆