[PyQt] Monkeypatching QWebPage.userAgentForUrl

Detlev Offenbach detlev at die-offenbachs.de
Thu May 12 18:33:59 BST 2011


On Mittwoch, 11. Mai 2011, Gelonida G wrote:
> Hi,
> 
> I would like to send a custom useragent for any http access done from a
> certain python script.
> 
> So I assumed the way to go would be monkeypatching userAgentForUrl
> 
> I'm not sure, whether this is impossible to achieve or whether I made a
> mistake in patching.
> 
> This is my approach in my code before the creation of any QWebview.
> 
> from PyQt4.QtWebKit import QWebPage
> import PyQt4.QtGui
> 
> 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
> 
> 
> patch_agent()
> print "PATCHED"
> 
> 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?
> 
> thanks in advance for any explanations or suggestions how to change the
> user agent 'globally'

Why do you try to monkeypatch it? Subclassing QWebView and implementing just 
the overridden method is much cleaner and doesn't look like a hack.

Detlev
-- 
Detlev Offenbach
detlev at die-offenbachs.de


More information about the PyQt mailing list