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

7 html javascript python

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

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>
Run Code Online (Sandbox Code Playgroud)

Python 2.7脚本:

import urllib
page =  urllib.urlopen('testdata.html').read()
print page
Run Code Online (Sandbox Code Playgroud)

小智 8

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

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

webbrowser.open('file://' + os.path.realpath(filename))
Run Code Online (Sandbox Code Playgroud)

要么

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)
Run Code Online (Sandbox Code Playgroud)

  • :- import webbrowser new = 2 # 如果可能的话,在新选项卡中打开 url = "file://C:/Users/S/Desktop/Python/testdata.html" webbrowser.open(url,new=new). 它只是打开记事本文件 (2认同)
  • 要在新选项卡中打开 URL,也可以使用“webbrowser.open_new_tab(url)”。 (2认同)

Yuv*_*uss 5

import os
os.system("start [your's_url]")
Run Code Online (Sandbox Code Playgroud)

请享用!


小智 5

您可以使用webbrowser库:

import webbrowser
url = 'file:///path/to/your/file/testdata.html'
webbrowser.open(url, new=2)  # open in new tab
Run Code Online (Sandbox Code Playgroud)