1
此程序是一個旨在規避代理設置的瀏覽器。正如你可以看到數據處理的時候,它被放到一個文件中並在默認瀏覽器中打開。然而,當我在Chrome中打開它(我不知道這是否是顯著),它說:爲什麼tempfile似乎在with語句中自己刪除?
This web page has not been found
No web page was found for the web address:
file:///C:/Users/Thornton/appdata/local/temp/tmpreb9zp.html
Error code: ERR_FILE_NOT_FOUND
下面是代碼:
import urllib.request
import webbrowser
import tempfile
from tkinter import *
class Browser:
def __init__(self, master):
global e1
self.proxy_handler = urllib.request.ProxyHandler(proxies=None)
self.opener = urllib.request.build_opener(self.proxy_handler)
Label(master, text='Full Path').grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Go', command=self.browse).grid(row=0, column=2)
root.bind('<Return>', self.browse)
@staticmethod
def parsed(data):
initial = str(data)[2:-1]
lines = initial.split('\\n')
return lines
def navigate(self, query):
response = self.opener.open(query)
html = self.parsed(response.read())
return html
def browse(self):
raw_data = self.navigate(e1.get())
clean_data = self.parsed(raw_data)
with tempfile.NamedTemporaryFile(suffix='.html') as cache:
cache.writelines(line.encode('UTF-8') for line in clean_data)
webbrowser.open_new_tab(cache.name)
root = Tk()
root.wm_attributes('-topmost', 1)
app = Browser(root)
root.mainloop()
我如何解決這個問題? –
NamedTemporaryFile使用關鍵字參數'delete = False'。也許用那個?這些都在文檔中。 – tuomur