How to make request through proxy in PyQt4

2019-03-16 23:29发布

I want to make a request through a HTTP proxy, the thing is I don't really understand how to set it up.

Here is an example code:

#! /usr/bin/env python2.7

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from bs4 import BeautifulSoup
import sys

class MySettings(QWebPage):
    def __init__(self):
        QWebPage.__init__(self)
        self.settings().setAttribute(QWebSettings.AutoLoadImages, False)

class Browser(QWebView):
    def __init__(self):
        QWebView.__init__(self)
        self.setPage(MySettings())
        self.loadProgress.connect(self._progress)
        self.loadFinished.connect(self._loadFinished)
        self.doc = self.page().currentFrame()

    def _progress(self, progress):
        print progress

    def _loadFinished(self):
        html = unicode(self.doc.toHtml()).encode('utf-8')
        soup = BeautifulSoup(html[1000])
        print soup.prettify()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    br = Browser()
    url = QUrl('http://http://ip2location.com/')
    br.load(url)
    br.show()
    app.exec_()

I have read about the QNetworkAccessManager class but don't understand where should I put it or should I create a different class like I did with QWebPage like so:

class MyNetworkAccessManager(QNetworkAccessManager):
    def __init__(self):
        QNetworkAccessManager.__init__(self)
        proxy = QNetworkProxy('HTTP','127.0.0.1', '8080') 
        self.setProxy(proxy)

If so, how to make my Browser(QWebView) class use MyNetworkAccessManager,

or may be I'm tottaly wrong, and it should be done differently.

Thank you very much for any help.

1条回答
时光不老,我们不散
2楼-- · 2019-03-17 00:07

To use the QNetworkAccessManager subclass your created, add this code to your Browser

old_manager = self.page().networkAccessManager()
new_manager = MyNetworkAccessManager(old_manager)
self.page().setNetworkAccessManager(new_manager)
查看更多
登录 后发表回答