Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the User-Agent for a QNetworkRequest in PyQtWebkit?

I'm trying to set the header "User-Agent" in my little webkit-browser, but I did not get.

That piece of code:

self.web = QtWebKit.QWebView(self)
...
self.request = QNetworkRequest() 
self.request.setUrl(url) 
self.request.setRawHeader("User-Agent", QtCore.QByteArray ("TestUserAgent")) 
self.request.setRawHeader("Accept-Language", QtCore.QByteArray ("en ,*")) 
self.web.load(self.request) 

In this example, "Accept-Language" is set correctly, but the "User-Agent" is always the default value. Tell me please, why? How do I set the "User-Agent"?

Thanks for help.

like image 836
Fedor Avatar asked Mar 15 '11 20:03

Fedor


2 Answers

QWebView overrides the QNetworkRequest field and sets the User-Agent header appropriate for the version of WebKit you are using. To change this default behavior you must inherit from QWebPage, reimplement QWebPage.userAgentForUrl and set the page for your QWebView instances to an instance of your new QWebPage type using QWebView.setPage.

like image 69
Judge Maygarden Avatar answered Oct 05 '22 02:10

Judge Maygarden


Ok, I figure out now :

class Browser(QtWebKit.QWebPage):
    def __init__(self):
        super(QtWebKit.QWebPage, self).__init__()

    def userAgentForUrl(self, url):
        return "Mozilla/5.0 (X11; Linux x86_64; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"

(it's an example)

Thanks to http://www.riverbankcomputing.com/pipermail/pyqt/2011-May/029826.html and http://pastebin.com/m1b350244

like image 39
Gilles Quenot Avatar answered Oct 05 '22 03:10

Gilles Quenot