我正在尝试设置url并使用PyQt捕获快照,代码适用于一个网址:
#!/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_())
但是当它通过一个快照时,它只是挂起并且不会继续下一个快照。那是为什么?
答案 0 :(得分:1)
您粘贴的代码的缩进并不能说明您的for
循环走了多远 - 我假设每一个循环都在循环中?
如果是这样,那么很明显为什么你的代码不起作用:你打电话给app.exec_
,它会一直阻止,直到最后一个窗口关闭或你拨打quit
或exit
。正如你从未做过的那样,它会永远阻挡。
如果您想以这种方式处理多个网址,则应使用事件处理程序保存网页并加载下一个网址。这样的事情应该有效:
#!/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_())