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

41
我正在尝试从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>

Python 2.7脚本:

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

1
可能是Python中webbrowser.open()的重复问题 - Jace Browning
8个回答

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

2
  • 导入webbrowser模块 new = 2 # 如果可能的话,在新标签页中打开 url = "file://C:/Users/S/Desktop/Python/testdata.html" webbrowser.open(url,new=new)。它只会打开记事本文件
- user7135817
1
第二个例子不起作用,只需使用完整路径到 html 文件,而不需要 file:// 前缀。 - Pedro Lobito
2
要在新标签页中打开URL,也可以使用webbrowser.open_new_tab(url) - and1er

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

享受!


有没有办法打开本地HTML文档,而不是在Plotly网页上显示它? - user7135817
请查看下面的答案 #Nayan Godhani - user3146115

11
您可以使用 webbrowser 库:
import webbrowser
url = 'file:///path/to/your/file/testdata.html'
webbrowser.open(url, new=2)  # open in new tab

4
这里有一个不需要外部库,也可以处理本地文件的方法。
import subprocess
import os

url = "https://stackoverflow.com"
# or a file on your computer
# url = "/Users/yourusername/Desktop/index.html
try: # should work on Windows
    os.startfile(url)
except AttributeError:
    try: # should work on MacOS and most linux versions
        subprocess.call(['open', url])
    except:
        print('Could not open URL')

2
你可以使用Selenium。
下载最新的chromedriver,将chromedriver.exe粘贴至"C:\Python27\Scripts"文件夹中。
然后,
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("your page path")
print driver.page_source.encode('utf-8')
driver.quit()
display.stop()

1
我觉得这是最简单的解决方案:

import os

os.getcwd() #To check the current working directory or path
os.chdir("D:\\Folder Name\\") # D:\Folder Name\ is the new path where you want to save the converted dataframe(df) to .html file

import webbrowser

df.to_html("filename.html") #Converting dataframe df to html and saving with a name 'filename' and 
webbrowser.get("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s").open("file://" + os.path.realpath("filename.html"))

0
import os
os.system('open "/Applications/Safari.app" '+ '"' + os.path.realpath(fname)+ '"')

这个答案对于那些发现这个问题并且只想使用Safari从Mac打开文件的人来说具有巨大的价值,因为“open”是一个Unix命令。您能否包含一条注释说明这一点,并包括fname的示例定义。继续保持良好的工作。 - Danoram

0

您可以从这里下载最新版本的“gecodriver”。然后将gecodriver可执行文件添加到您的项目中。接下来在Windows上使用以下代码安装selenium:

from selenium import webdriver   
from selenium.webdriver.firefox.options import Options   
import os

#optional
options = Options()   
options.set_preference('permissions.default.image', 2)   
options.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', False)   

#for windows
Driver = webdriver.Firefox(options=options, executable_path='geckodriver.exe')   
Driver.implicitly_wait(15)

#path of your project -> reference : "https://dev59.com/DF8e5IYBdhLWcg3wwMv8#40227116"   
Root = os.path.dirname(os.path.abspath(__file__))    
driver.get('file://' + Root + 'path/to/htmlfile')

希望我能帮到你 :)


非常感谢您发布有关Selenium使用的教程。然而,用户只想在单击链接时打开浏览器,就像在PDF(或Word)文档中一样。 - Elis Byberi
我知道,但我希望任何使用Selenium的人,无论是专业人士还是初学者,在看到这篇文章后都可以毫无问题地使用它。例如,我用它创建了机器智能爬虫,但这个用户可以删除选项和根部分。 - PouriaDiesel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接