Set a custom User-Agent for QWebEngine (in PyQt5)
-
I read a couple of questions on how to set a custom user-agent for your browser, but couldn't make it work.
Mainly I followed these steps:
https://stackoverflow.com/questions/5317924/how-do-i-set-the-user-agent-for-a-qnetworkrequest-in-pyqtwebkit
https://pastebin.com/m1b350244
and subclassed QWebEnginePage with a userAgentForUrl function as they instructed. My Apache server has been rigged to let you pass only if your user-agent is "Ree", but I get a 403 Forbidden error, so I think this code doesn't send the user-agent:from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtWebEngineWidgets import * USER_AGENT = "Ree" class WebPage(QWebEnginePage): def __init__(self): super(QWebEnginePage, self).__init__() def userAgentForUrl(self, url): return USER_AGENT class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.resize(1024, 800) widget = QWidget() self.setCentralWidget(widget) self.webview = QWebEngineView(self) self.page = WebPage() self.webview.setPage(self.page) vbox = QVBoxLayout() vbox.addWidget(self.webview) widget.setLayout(vbox) def loadUrl(self, url): self.webview.load(QUrl(url)) self.webview.show() if __name__ == "__main__": import sys app = QApplication(sys.argv) window = MainWindow() window.loadUrl("http://127.0.0.1") window.show() sys.exit(app.exec_())
Does it have something to do with the fact that userAgentForUrl function takes a url but it doesn't receive one?
-
@Harborman userAgentForUrl is for QWebPage from QtWebkit, for QtWebEngine you must use
QWebEngineProfile::setHttpUserAgent()
:import sys from PyQt5.QtCore import QUrl from PyQt5.QtWebEngineWidgets import QWebEngineView from PyQt5.QtWidgets import QApplication if __name__ == "__main__": app = QApplication(sys.argv) web = QWebEngineView() web.page().profile().setHttpUserAgent("Ree") web.load(QUrl("http://127.0.0.1")) web.show() web.resize(640, 480) sys.exit(app.exec_())