[PyQt] Monkeypatching QWebPage.userAgentForUrl

David Boddie david at boddie.org.uk
Fri May 13 16:23:57 BST 2011


On Wed May 11 22:41:13 BST 2011, Gelonida G wrote:

> def patch_agent():
>     old_userAgentForUrl =  QWebPage.userAgentForUrl
>     def new_userAgentForUrl(self, url):
>         """ for demo purposes I just added logging """
>         rslt = old_userAgentForUrl(self, url)
>         print "agent is %s" % rslt
>         return rslt
>     QWebPage.userAgentForUrl = new_userAgentForUrl

[...]

> app = PyQt4.QtGui.QApplication(sys.argv)
> webview = QWebView()
> webview.setHtml("""<a href="http://www.google.com">Search</a>""")
> webview.show()
> sys.exit(app.exec_())
>
> Somehow it seems, that the my patched method is never called.
>
> What could be the reason?

My intuition is that the monkey-patching will only work for QWebPage
instances created by PyQt. Since the QWebPage instance shown in the QWebView 
is created by Qt, you get a regular, unpatched instance instead.

If you want to use your patched QWebPage, call QWebView's setPage() method
with one of your patched instances.

David


More information about the PyQt mailing list