0

我正在尝试使用 PyQt 转到一组 url 并捕获那里的快照,该代码适用于一个 url:

#!/usr/bin/env python
import sys, itertools
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage

urls = "http://www.gouvernement.fr/", "http://www.google.com/"
outputs = "output1.png", "output2.png"
 #for url in urls: #and output in ouputs:
for url, output in itertools.izip(urls, outputs):

    def onLoadFinished(result):
    if not result:
        print "Request failed"
        sys.exit(1)

    # Set the size of the (virtual) browser window
    webpage.setViewportSize(webpage.mainFrame().contentsSize())

    # Paint this frame into an image
    image = QImage(webpage.viewportSize(), QImage.Format_ARGB32)
    painter = QPainter(image)
    webpage.mainFrame().render(painter)
    painter.end()
    image.save(output)
    print ".png image successfully saved"
    #sys.exit(0)


    app = QApplication(sys.argv)
    signal.signal(signal.SIGINT, signal.SIG_DFL)

    webpage = QWebPage()
    webpage.connect(webpage, SIGNAL("loadFinished(bool)"), onLoadFinished)
    webpage.mainFrame().load(QUrl(url))
    sys.exit(app.exec_())

但是当它通过一个快照时,它只是挂起并且不会继续进行下一个快照。这是为什么 ?

4

1 回答 1

1

您粘贴的代码的缩进并不能清楚地说明您的for循环走了多远 - 我假设每次都在循环内?

如果是这样,那么很清楚为什么您的代码不起作用:您调用app.exec_,它将阻塞直到最后一个窗口关闭或您调用quitor exit。你从来没有这样做过,它会永远阻塞。

如果你想以这种方式处理多个 url,你应该使用你的事件处理程序来保存页面并加载下一个 url。像这样的东西应该工作:

#!/usr/bin/env python
import sys, itertools
import signal
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage

urls = ["http://www.gouvernement.fr/", "http://www.google.com/"]
outputs = ["output1.png", "output2.png"]

def save_page(webpage, output):
    # Set the size of the (virtual) browser window
    webpage.setViewportSize(webpage.mainFrame().contentsSize())

    # Paint this frame into an image
    image = QImage(webpage.viewportSize(), QImage.Format_ARGB32)
    painter = QPainter(image)
    webpage.mainFrame().render(painter)
    painter.end()
    image.save(output)
    print ".png image successfully saved"
    #sys.exit(0)


app = QApplication(sys.argv)
signal.signal(signal.SIGINT, signal.SIG_DFL)

webpage = QWebPage()

def onLoadFinished(result):
    if not result:
        print "Request failed"
        sys.exit(1)
    save_page(webpage, outputs.pop(0))   # pop output name from list and save
    if urls:
        url = urls.pop(0)   # pop next url to fetch from list
        webpage.mainFrame().load(QUrl(url))
    else:
        app.quit()  # exit after last url

webpage.connect(webpage, SIGNAL("loadFinished(bool)"), onLoadFinished)
webpage.mainFrame().load(QUrl(urls.pop(0)))
sys.exit(app.exec_())
于 2013-07-29T18:54:51.410 回答