QWebpage只取HTML一次,不能再次调用

QWebpage only fetches HTML once, and cannot be invoked again

我有一个代码:

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

class TextBrowser(QtCore.QObject):

    def __init__(self, url):
        self.some_url = url

        self.html_source = None

        QtCore.QObject.__init__(self)
        self.page = QWebPage()

        self.page.loadFinished.connect(self.get_html)

        self.page.mainFrame().load(self.some_url)

    def get_html(self):
        frame = self.page.mainFrame()
        self.html_source = unicode(frame.toHtml()).encode('utf-8')
        QtCore.QCoreApplication.quit()


def get_html_source(some_url):
    app = QApplication([])
    browser = TextBrowser(QtCore.QUrl(some_url))
    app.exec_()
    return browser.html_source

所以现在,如果我 运行:

print get_html_source('http://www.google.com')

没关系,returns 来自页面 http://www.google.com 的 html 来源。但是如果我 运行 另一个像这样的下一个:

print get_html_source('http://www.google.com')
print get_html_source('http://www.yahoo.com/')

这只执行一次,输出 google 的 html 源,但之后 PyCharm returns "Process finished with exit code 139" 和 [=28 的第二次调用=]() 没有执行。

我需要遍历一些 url 列表并通过 Qwebpage 从中获取源代码,但我的实现不起作用。

我在哪里可以找到有关我的需求或我做错了什么的信息?

考虑以下问题。 exec_ 启动事件循环(一次),两个单独的页面是 运行:

from PyQt4 import QtCore, QtGui
from PyQt4.QtWebKit import QWebPage
from PyQt4.QtGui import QApplication

class TextBrowser(QtGui.QDialog):

    def __init__(self, url):
        self.some_url = url

        QtCore.QObject.__init__(self)
        self.page = QWebPage()
        self.page.loadFinished.connect(self.get_html)
        self.page.mainFrame().load(self.some_url)

    def get_html(self):
        frame = self.page.mainFrame()
        self.html = frame.toHtml()
        self.close()


def get_html_source():
    app = QApplication([])
    urls = ['http://www.google.com', 'http://www.yahoo.com/']
    out = []
    for u in urls:
        t = TextBrowser(QtCore.QUrl(u))
        t.exec_()
        out.append(t.html)
    print(out)

if __name__ == "__main__":
    get_html_source()

这个程序无法按原样退出 - 我想你想用 HTML 做更多的事情而不是打印它。