ホームページ  >  記事  >  バックエンド開発  >  Qt で QWebPage を使用して複数の URL を効率的に取得するにはどうすればよいですか?

Qt で QWebPage を使用して複数の URL を効率的に取得するにはどうすればよいですか?

DDD
DDDオリジナル
2024-10-27 11:42:30576ブラウズ

How to Efficiently Retrieve Multiple URLs Using QWebPage in Qt?

QWebPage を使用して複数の URL を取得する

このシナリオでは、Qt の QWebPage を使用して動的に更新されるページをレンダリングしようとしました。ただし、2 番目のページをレンダリングしようとすると、頻繁にクラッシュが発生しました。

問題分析

問題はアプローチにあります。 URL フェッチごとに新しい QApplication と QWebPage を初期化しています。代わりに、シグナルとカスタム処理を使用して同じインスタンス内の複数の URL を処理し、単一の QApplication と QWebPage を維持することをお勧めします。

提案されたソリューション

WebPage クラス

以下は PyQt5 と PyQt4 の両方のカスタム WebPage クラスです:

PyQt5 WebPage

<code class="python">from PyQt5.QtCore import pyqtSignal, QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEnginePage

class WebPage(QWebEnginePage):
    htmlReady = pyqtSignal(str, str)

    def __init__(self, verbose=False):
        super().__init__()
        self._verbose = verbose
        self.loadFinished.connect(self.handleLoadFinished)

    def process(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try:
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.load(QUrl(url))
        return True

    def processCurrentPage(self, html):
        self.htmlReady.emit(html, self.url().toString())
        if not self self.fetchNext():
            QApplication.instance().quit()

    def handleLoadFinished(self):
        self.toHtml(self.processCurrentPage)

    def javaScriptConsoleMessage(self, *args, **kwargs):
        if self._verbose:
            super().javaScriptConsoleMessage(*args, **kwargs)</code>

PyQt4 WebPage

<code class="python">from PyQt4.QtCore import pyqtSignal, QUrl
from PyQt4.QtGui import QApplication
from PyQt4.QtWebKit import QWebPage

class WebPage(QWebPage):
    htmlReady = pyqtSignal(str, str)

    def __init__(self, verbose=False):
        super(WebPage, self).__init__()
        self._verbose = verbose
        self.mainFrame().loadFinished.connect(self.handleLoadFinished)

    def process(self, urls):
        self._urls = iter(urls)
        self.fetchNext()

    def fetchNext(self):
        try: 
            url = next(self._urls)
        except StopIteration:
            return False
        else:
            self.mainFram().load(QUrl(url))
        return True

    def processCurrentPage(self):
        self.htmlReady.emit(self.mainFrame().toHtml(), self.mainFrame().url().toString())
        if not self.fetchNext():
            QApplication.instance().quit()

    def javaScripConsoleMessage(self ,* args, **kwargs):
        if self._verbose:
            super(WebPage, self).javaScriptConsoleMessage(*args, **kwargs)</code>

使用法

これらの WebPage クラスの使用方法の例を次に示します。

<code class="python">from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication

# PyQt5
url_list = ['https://example.com', 'https://example2.com']
app = QApplication(sys.argv)
webpage = WebPage(verbose=True)
webpage.htmlReady.connect(my_html_processor)
webpage.process(url_list)
sys.exit(app.exec_())

# PyQt4
from PyQt4.QtCore import QUrl
from PyQt4.QtGui import QApplication
url_list = ['https://example.com', 'https://example2.com']
app = QApplication(sys.argv)
webpage = WebPage(verbose=True)
webpage.htmlReady.connect(my_html_processor)
webpage.process(url_list)
sys.exit(app.exec_())</code>

このコードでは、my_html_processor は、処理された HTML を処理するようにカスタマイズできる関数であり、各ページの URL 情報。

このアプローチを実装すると、以前に発生したクラッシュやランダムな動作を防ぐことができ、より安定した効率的な Web スクレイピング ワークフローが実現します。

以上がQt で QWebPage を使用して複数の URL を効率的に取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。