如何在Python函数中执行QWebEngine

How to execute QWebEngine in Python function

我有一个 QWebEngine class 来读取网页并为它们创建 BeautifulSoup。

代码如下:

import sys
from bs4 import BeautifulSoup
import os


from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets


class WebPage(QtWebEngineWidgets.QWebEnginePage):
    def __init__(self):
        super(WebPage, self).__init__()
        self.loadFinished.connect(self.handleLoadFinished)
        self.soup = []

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

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

    def processCurrentPage(self, html):
        url = self.url().toString()
        self.soup.append(BeautifulSoup(html, 'lxml'))
        if not self.fetchNext():
            QtWidgets.qApp.quit()

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

这里是调用另一个函数 WebPage class:

def get_soup(urls):
    app = QtWidgets.QApplication(sys.argv)
    webpage = WebPage()
    webpage.start(urls)
    return webpage.soup

这里是 main:

if __name__ == "__main__":

    urls = ["http://www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=sh", "http://www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=sz"]      
    soups = get_soup(urls)

但是,当我执行程序时,程序重新启动了。

应该改变什么?

这是我已经遇到的问题,分析我发现QApplication在QWebEnginePage之前被销毁使得QWebEngineProfile被删除,在这种情况下导致QWebEnginePage崩溃。解决方案是通过将其设为全局变量来使应用程序具有更大的范围。

另一方面,您必须调用 exec_() 以便允许信号操作的事件循环

# ...
app = None

def get_soup(urls):
    global app
    app = QtWidgets.QApplication(sys.argv)
    webpage = WebPage()
    webpage.start(urls)
    app.exec_()
    return webpage.soup
# ...

注:看来QTBUG-75547 related to this problem has been solved for Qt5>=5.12.4 so probably in a next release of PyQtWebEngine那个bug不会再观察了