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

2024-04-26 06:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个密码:

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

所以现在,如果我运行:

^{pr2}$

没关系,从页面http://www.google.com返回一个html源代码。但如果我再运行一个这样的程序:

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

这只执行一次,输出google的html源代码,但之后PyCharm返回“Process finished with exit code 139”,并且第二次get_html_source()调用不会执行。在

我需要迭代一些url列表,并从中获取源代码,使用Qwebpage,但我的实现不起作用。在

我在哪里可以找到一些关于我的需求的信息,或者我做错了什么?在


Tags: fromimportselfhttpurlsourcegetdef
1条回答
网友
1楼 · 发布于 2024-04-26 06:34:59

考虑以下几点。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比打印它。在

相关问题 更多 >