2014-12-09 3 views
0

Python4 (QwebPage)에서 asynchrone (asyncio와 같은) 웹 요청을 수행 할 수 있습니까? 이 코드와 병렬로 여러 URL을 호출하는 방법을 예를 들어python3.4 Pyqt4 웹 요청 asyncio

:

#!/usr/bin/env python3.4 

import sys 
import signal 

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import QWebPage 

class Crawler(QWebPage): 
    def __init__(self, url): 
     QWebPage.__init__(self) 
     self._url = url 
     self.content = '' 

    def crawl(self): 
     signal.signal(signal.SIGINT, signal.SIG_DFL) 
     self.connect(self, SIGNAL('loadFinished(bool)'), self._finished_loading) 
     self.mainFrame().load(QUrl(self._url)) 

    def _finished_loading(self, result): 
     self.content = self.mainFrame().toHtml() 
     print(self.content) 
     sys.exit(0) 

    def main(): 
     app = QApplication(sys.argv) 
     crawler = Crawler(self._url, self._file) 
     crawler.crawl() 
     sys.exit(app.exec_()) 

if __name__ == '__main__': 
    crawl = Crawler('http://www.example.com') 
    crawl.main() 

감사

답변

1

을 당신은 asyncio을 통해 작업 self.mainFrame().load(QUrl(self._url))을 할 수 없습니다, 죄송합니다 - 방법은 Qt는 자체에서 구현.

그러나 이벤트 루프를 quamash 설치하고 비동기 적으로 aiohttp.request coroutine을 호출하여 웹 페이지를 가져올 수 있습니다.

그래도 QWebPage과 작동하지 않습니다.

+0

안녕 앤드류, 감사 :

여기에 간단한 귀하의 예제 스크립트를 기반으로 데모입니다. aiohttp로 QwebPage를 대체하면 비동기 호출을 수행 할 수 있습니까? 아니면 모든 코드를 수정해야합니까? – Matt

+0

답변은 필요에 따라 다릅니다. 나중에 분석을 위해 async가 요청하는 HTTP 요청이 요구 사항 (예 : Qt 인터페이스의 Scrapy와 같은 것을 작성하는 경우)을 충족시키는 경우 - aiohttp가 도움이 될 수 있습니다. –

+0

aiohttp에서 PyQT4를 사용하는 예가 있습니까? 왜냐하면 두 가지를 함께 사용하려고 시도했기 때문에 작동하지 않습니다. – Matt

0

요청은 이미 비동기 적으로 완료되었으므로 QWebPage의 여러 인스턴스를 생성하면됩니다. 답장을 보내

import sys, signal 
from PyQt4 import QtCore, QtGui, QtWebKit 

urls = [ 
    'http://qt-project.org/doc/qt-4.8/qwebelement.html', 
    'http://qt-project.org/doc/qt-4.8/qwebframe.html', 
    'http://qt-project.org/doc/qt-4.8/qwebinspector.html', 
    'http://qt-project.org/doc/qt-4.8/qwebpage.html', 
    'http://qt-project.org/doc/qt-4.8/qwebsettings.html', 
    'http://qt-project.org/doc/qt-4.8/qwebview.html', 
    ] 

class Crawler(QtWebKit.QWebPage): 
    def __init__(self, url, identifier): 
     super(Crawler, self).__init__() 
     self.loadFinished.connect(self._finished_loading) 
     self._id = identifier 
     self._url = url 
     self.content = '' 

    def crawl(self): 
     self.mainFrame().load(QtCore.QUrl(self._url)) 

    def _finished_loading(self, result): 
     self.content = self.mainFrame().toHtml() 
     print('[%d] %s' % (self._id, self._url)) 
     print(self.content[:250].rstrip(), '...') 
     print() 
     self.deleteLater() 

if __name__ == '__main__': 

    app = QtGui.QApplication(sys.argv) 
    signal.signal(signal.SIGINT, signal.SIG_DFL) 
    crawlers = [] 
    for index, url in enumerate(urls): 
     crawlers.append(Crawler(url, index)) 
     crawlers[-1].crawl() 
    sys.exit(app.exec_()) 
관련 문제