2016-12-03 193 views
0

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

这意味着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() 

回答

0
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) 
+0

移动文件名的声明没有奏效。如果html文件与记事本相关联,则记事本出现,而不是默认浏览器 – bobv

+0

@Bobv它可能是web浏览器模块不打开本地文件。尝试sub process.popen()这里建议http://stackoverflow.com/questions/15054434/how-can-i-open-files-in-external-programs-in-python – mcmxl

+0

谢谢,subprocess.Popen()似乎在工作。 – bobv