此程序是一个旨在规避代理设置的浏览器。正如您所看到的那样,处理数据时会将其放入文件中并在默认浏览器中打开。但是当我用chrome打开它时(我不知道这是否有意义),它说:
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()
答案 0 :(得分:2)
因为临时文件是deleted when closed,而with
语句就是这样,并且webbrowser模块不等待完成。来自documentation:
对于非Unix平台,或者在Unix上提供远程浏览器时, 控制过程不会等待用户完成 浏览器