我正在使用wx.html2.WebView在对话框中加载网站,工作正常。
问题:如果由于任何原因无法访问网站,输出将为无法连接:连接被拒绝
。
期望的行为:尝试在每次失败 x 秒后重新加载 URL。
import wx
import wx.html2
import time
URL = "http://mydomain.tld"
class MyBrowser(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.browser = wx.html2.WebView.New(self)
self.browser.Bind(wx.html2.EVT_WEBVIEW_ERROR, self.on_webview_error)
def on_webview_error(self, evt):
# Printing works
print("Error: can't load page, try again in 3 seconds.")
# Sleeping works
time.sleep(3)
# Reloading doesn't work
self.browser.LoadURL(URL) # OR self.browser.Reload()
# Weird: Error is rendered now
if __name__ == '__main__':
app = wx.App()
dialog = MyBrowser(None, -1)
dialog.browser.LoadURL(URL)
dialog.Show()
app.MainLoop()
问题出现在on_webview_error(self, evt)
中。我的猜测是我没有正确使用该函数,特别是因为错误消息是在重新加载后呈现的。
有什么想法吗?
提前致谢!
最佳答案
那里发生了一些奇怪的事情!
我可以强制它工作的唯一方法是每次重新定义 WebView
。我可能每次都对Destroy
过于热心。
这可行,但不一定正是您所追求的。
import wx
import wx.html2
import time
URL = "http://mydomain.tld"
class MyBrowser(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.url = URL
self.browser = wx.html2.WebView.New(self, -1, size=(900,600))
self.browser.Bind(wx.html2.EVT_WEBVIEW_ERROR, self.on_webview_error)
self.browser.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.on_webview_load)
self.retries = 0
self.max_retries = 10
def on_webview_error(self, evt):
self.URL = evt.GetURL()
print(self.URL)
self.retries += 1
if self.retries > self.max_retries: # Give up
self.Destroy()
print("Error {} of {} attempts to load {}, trying again in 3 seconds.".format(self.retries,self.max_retries,self.URL))
if self.retries > 5: # Try alternate
self.URL = "http://wxPython.org"
print("Swapping to alternate Url "+self.URL)
self.browser.Destroy()
time.sleep(3)
self.browser = wx.html2.WebView.New(self, -1, size=(900,600))
self.browser.Bind(wx.html2.EVT_WEBVIEW_ERROR, self.on_webview_error)
self.browser.Bind(wx.html2.EVT_WEBVIEW_LOADED, self.on_webview_load)
self.browser.LoadURL(self.URL)
def on_webview_load(self, evt):
print(self.URL, "Load complete")
if __name__ == '__main__':
app = wx.App()
dialog = MyBrowser(None, -1)
dialog.browser.LoadURL(URL)
dialog.Show()
app.MainLoop()
关于python - wxPython WebView : how to reload on error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55704990/