【问题标题】:Python webbrowser not opening browserPython webbrowser没有打开浏览器
【发布时间】:2016-12-03 19:05:42
【问题描述】:

我正在尝试熟悉 Python,主要关注网络发布,所以我环顾四周,找到了以下示例。在 Windows 7 上的 PyScripter 中运行 2.7 并没有像我预期的那样启动浏览器。代码出现在 Notepad++ 中,显然是因为 html 后缀与记事本相关联。我尝试了十几种不同的代码排列方式,但 html 文件仍然在记事本中打开,直到我将该文件与 Firefox 相关联。当我包含 print webbrowser._browsers 命令时,我得到 {'windows-default': [, None], 'c:\program files (x86)\internet explorer\iexplore.exe': [None, ]}

这对我来说意味着 IE 应该是被调用的默认浏览器,但显然不是。谁能在这里启发我,因为我是 Python 新手?

'''A simple program to create an html file froma given string,
and call the default web browser to display the file.'''

contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
  <meta content="text/html; charset=ISO-8859-1"
 http-equiv="content-type">
  <title>Hello</title>
</head>
<body>
Hello, World!
</body>
</html>
'''

import webbrowser

def main():
    browseLocal(contents)

def strToFile(text, filename):
    """Write a file with the given name and the given text."""
    output = open(filename,"w")
    output.write(text)
    output.close()

def browseLocal(webpageText, filename='C:\\Python27\\Programs\\tempBrowseLocal.html'):
    '''Start your webbrowser on a local file containing the text
    with given filename.'''
    strToFile(webpageText, filename)
    print webbrowser._browsers
    webbrowser.open(filename)


main()

【问题讨论】:

    标签: python-2.7


    【解决方案1】:
    def browseLocal(webpageText):#take filename out of here
        '''Start your webbrowser on a local file containing the text
        with given filename.'''
        #define filename here.
        filename='C:\\Python27\\Programs\\tempBrowseLocal.html'
        strToFile(webpageText, filename)
        print webbrowser._browsers
        webbrowser.open(filename)
    

    【讨论】:

    • 移动文件名声明无效。如果 html 文件与记事本相关联,则会出现记事本,而不是默认浏览器
    • @Bobv 可能是 webbrowser 模块没有打开本地文件。按照这里的建议尝试子 process.popen() stackoverflow.com/questions/15054434/…
    猜你喜欢
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2019-04-12
    • 2014-04-22
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多