我有一个QWebEngine类,可以读取网页并为其创建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
类的函数:
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)
但是,当我执行程序时,程序会重新启动。
应该更改什么?
答案 0 :(得分:2)
这是我已经遇到的一个问题,分析发现我发现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在Qt5> = 5.12.4中已解决,因此在下一版PyQtWebEngine中,该错误可能会不再被观察。