Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect QWebEngine to proxy

I created my own proxy to intercept packets on 127.0.0.1:6666, and I want it so all packets sent from QWebEngine gets sent to the proxy. I looked this up and I found a few websites saying to use QNetworkProxy, but it never showed how to get it to work properly.

Here is a code sample I found online for just a normal QWebEngine program (it works fine)

from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
  def setupUi(self, MainWindow):
    MainWindow.setObjectName("MainWindow")
    MainWindow.resize(800, 600)
    self.centralwidget = QtWidgets.QWidget(MainWindow)
    self.centralwidget.setObjectName("centralwidget")
    self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
    self.gridLayout.setObjectName("gridLayout")
    self.webView = QtWebEngineWidgets.QWebEngineView(self.centralwidget)
    self.webView.setUrl(QtCore.QUrl("http://www.google.com/"))
    self.webView.setObjectName("webView")
    self.gridLayout.addWidget(self.webView, 0, 0, 1, 1)
    MainWindow.setCentralWidget(self.centralwidget)
    self.statusbar = QtWidgets.QStatusBar(MainWindow)
    self.statusbar.setObjectName("statusbar")
    MainWindow.setStatusBar(self.statusbar)
    self.retranslateUi(MainWindow)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
   def retranslateUi(self, MainWindow):
    _translate = QtCore.QCoreApplication.translate
    MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

from PyQt5 import QtWebEngineWidgets

if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)
   MainWindow = QtWidgets.QMainWindow()
   ui = Ui_MainWindow()
   ui.setupUi(MainWindow)
   MainWindow.show()
   sys.exit(app.exec_())

Now how do I make set the proxy settings or whatever to go to 127.0.0.1:6666?

like image 929
EmperorBale Avatar asked Mar 06 '23 02:03

EmperorBale


1 Answers

As you indicate you have to use QNetworkProxy:

from PyQt5 import QtCore, QtGui, QtWidgets, QtNetwork

class Ui_MainWindow(object):
    ...

from PyQt5 import QtWebEngineWidgets

if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)

   proxy = QtNetwork.QNetworkProxy()
   proxy.setType(QtNetwork.QNetworkProxy.HttpProxy)
   proxy.setHostName("127.0.0.1")
   proxy.setPort(6666)
   QtNetwork.QNetworkProxy.setApplicationProxy(proxy)

   MainWindow = QtWidgets.QMainWindow()
   ui = Ui_MainWindow()
   ui.setupUi(MainWindow)
   MainWindow.show()
   sys.exit(app.exec_())
like image 156
eyllanesc Avatar answered Mar 16 '23 00:03

eyllanesc