Python QtWebKit 将网页保存为文件

4 投票
2 回答
4646 浏览
提问于 2025-04-17 02:22

如何将用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 个回答

0

有没有什么特别的原因需要先用QtWebKit加载这个页面呢?其实,直接用命令行工具wget或者curl就可以完成这个任务。

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_())

撰写回答