如何在 PyQt4 中通过代理发出请求 [英] How to make request through proxy in PyQt4

查看:70
本文介绍了如何在 PyQt4 中通过代理发出请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 HTTP 代理发出请求,问题是我不太明白如何设置.

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

这是一个示例代码:

#! /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_()

我已经阅读了 QNetworkAccessManager 类,但不明白我应该把它放在哪里,或者我应该像使用 QWebPage 那样创建一个不同的类:

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)

如果是这样,如何让我的浏览器(QWebView)类使用 MyNetworkAccessManager,

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

或者可能是我完全错了,应该以不同的方式来做.

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

非常感谢您的帮助.

推荐答案

要使用您创建的 QNetworkAccessManager 子类,请将此代码添加到您的 Browser

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)

这篇关于如何在 PyQt4 中通过代理发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆