The indenting of the code you pasted doesn't make it clear how far your for
loop goes - I presume everyting until the end is within the loop?
If so, then it's clear why your code doesn't work: you call app.exec_
, which will block until the last window is closed or you call quit
or exit
. As you never do, it blocks forever.
If you want to process multiple urls this way, you should use your event handlers to save the page and load the next url. Something like this should work:
#!/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_())