我正在尝试使用QNetworkAccessManager访问网络请求网址

在此示例Threading with webkit中,我已将NetWorkAccessManager附加到现有代码,但是该页面根本没有加载我的代码。

import sys
from collections import deque # threadsafe datatype
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from PyQt4.QtNetwork import *
NUM_THREADS = 2 # how many threads to use

class Render(QWebView):
    active = deque() # track how many threads are still active
    data = {} # store the data

    def __init__(self, urls):
        QWebView.__init__(self)

        # I have Added the following code
        manager = Manager()
        page = self.page()
        page.setNetworkAccessManager(manager)

        self.loadFinished.connect(self._loadFinished)
        self.urls = urls
        self.crawl()

    def crawl(self):
        try:
            url = self.urls.pop()
            print 'downloading', url
            Render.active.append(1)
            self.load(QUrl(url))
        except IndexError:
            # no more urls to process
            if not Render.active:
                # no more threads downloading
                print 'finished'
                self.close()

    def _loadFinished(self, result):
        # process the downloaded html
        frame = self.page().mainFrame()
        url = str(frame.url().toString())
        Render.data[url] = frame.toHtml()
        Render.active.popleft()
        self.crawl() # crawl next URL in the list

# I have Added the following class
class Manager(QNetworkAccessManager):
    def __init__(self):
        print 'entered network manager'
        QNetworkAccessManager.__init__(self)
        self.finished.connect(self._finished)

    def _finished(self, reply):
        print 'finished network req event'
        url = reply.url().toString()
        print url.toUtf8()

app = QApplication(sys.argv) # can only instantiate this once so must move outside class
urls = deque(['http://www.google.com/', 'http://stackoverflow.com/'])
renders = [Render(urls) for i in range(NUM_THREADS)]
app.exec_() # will execute qt loop until class calls close event


我在这里做错了什么?

最佳答案

只需添加self.setPage(page)设置page.setNetworkAccessManager(manager)之前

关于python - Python QWebView:访问网络资源,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35152118/

10-09 06:05