Python QtWebKit保存网页到文件

4
什么是使用QWebView()来保存网页为文件的最佳和最简单的方法?
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from PyQt4.QtGui import *
from PyQt4.QtScript import *
import sys
import time

currentfile = "test.htm"
app = QApplication(sys.argv)
web = QWebView()
web.load(QUrl("http://news.google.com"))
web.show()
data =  web.page().currentFrame().documentElement().toInnerXml()
open(currentfile,"w").write(data)
sys.exit(app.exec_())
2个回答

6
作为页面加载是异步的,所以在尝试保存之前必须等待“loadFinished”信号。然后,您可以使用“web.page().currentFrame().toHtml()”检索页面内容,该函数返回一个Python Unicode字符串,您可以使用codecs模块将其写入文件中。
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *
import sys
import codecs

class Downloader(QObject):
    # To be emitted when every items are downloaded
    done = Signal()

    def __init__(self, urlList, parent = None):
        super(Downloader, self).__init__(parent)
        self.urlList = urlList
        self.counter = 0        
        # As you probably don't need to display the page
        # you can use QWebPage instead of QWebView
        self.page = QWebPage(self)      
        self.page.loadFinished.connect(self.save)
        self.startNext()

    def currentUrl(self):
        return self.urlList[self.counter][0]

    def currentFilename(self):
        return self.urlList[self.counter][1]

    def startNext(self):
        print "Downloading %s..."%self.currentUrl()
        self.page.mainFrame().load(self.currentUrl())

    def save(self, ok):
        if ok:            
            data = self.page.mainFrame().toHtml()
            with codecs.open(self.currentFilename(), encoding="utf-8", mode="w") as f:
                f.write(data)
            print "Saving %s to %s."%(self.currentUrl(), self.currentFilename())            
        else:
            print "Error while downloading %s\nSkipping."%self.currentUrl()
        self.counter += 1
        if self.counter < len(self.urlList):            
            self.startNext()
        else:
            self.done.emit()

urlList = [("http://news.google.com", "google.html"), 
    ("http://www.stackoverflow.com","stack.html"), 
    ("http://www.imdb.com", "imdb.html")]

app = QApplication(sys.argv)
downloader = Downloader(urlList)
# Quit when done
downloader.done.connect(app.quit)

# To view the pages
web = QWebView()
# To prevent user action that would interrupt the current page loading
web.setDisabled(True) 
web.setPage(downloader.page)
web.show()

sys.exit(app.exec_())

非常感谢!;) 只有一个快速的问题:迭代多个链接的最佳方法是什么? - Cat
save()函数的末尾,你可以简单地更改currentfile中的文件名,并使用下一个URL调用web.load(),而不是使用app.quit() - alexisdm
这就是我想做的,但它似乎并没有真正等待第一个正确加载,而是在第一个URL上生成了下载错误... - Cat
@Cat 我更新了代码,允许下载多个链接。你遇到的错误可能来自于变量作用域相关的问题。 - alexisdm
如何保存 HTML 支持的文件(JPEG、PNG、JS、CSS等),以便在打开保存的 HTML 时能够正确呈现。 - namit
显示剩余3条评论

0
页面需要先使用QtWebKit加载的原因是什么?只需使用命令行实用程序wget或curl即可完成工作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接