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()
移動文件名的聲明沒有奏效。如果html文件與記事本相關聯,則記事本出現,而不是默認瀏覽器 – bobv
@Bobv它可能是web瀏覽器模塊不打開本地文件。嘗試sub process.popen()這裏建議http://stackoverflow.com/questions/15054434/how-can-i-open-files-in-external-programs-in-python – mcmxl
謝謝,subprocess.Popen()似乎在工作。 – bobv