python - 如何使用 Python 截取网站的屏幕截图/图像?

标签 python screenshot webpage backend

我想要实现的是从 python 中的任何网站获取网站截图。

环境:Linux

最佳答案

这是一个使用 webkit 的简单解决方案: http://webscraping.com/blog/Webpage-screenshots-with-webkit/

import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

class Screenshot(QWebView):
    def __init__(self):
        self.app = QApplication(sys.argv)
        QWebView.__init__(self)
        self._loaded = False
        self.loadFinished.connect(self._loadFinished)

    def capture(self, url, output_file):
        self.load(QUrl(url))
        self.wait_load()
        # set to webpage size
        frame = self.page().mainFrame()
        self.page().setViewportSize(frame.contentsSize())
        # render image
        image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
        painter = QPainter(image)
        frame.render(painter)
        painter.end()
        print 'saving', output_file
        image.save(output_file)

    def wait_load(self, delay=0):
        # process app events until page loaded
        while not self._loaded:
            self.app.processEvents()
            time.sleep(delay)
        self._loaded = False

    def _loadFinished(self, result):
        self._loaded = True

s = Screenshot()
s.capture('http://webscraping.com', 'website.png')
s.capture('http://webscraping.com/blog', 'blog.png')

关于python - 如何使用 Python 截取网站的屏幕截图/图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1197172/

相关文章:

google-chrome - 是否需要同时在 Safari 和 Chrome 中测试网页?

Python:从同一个解释器同时执行多个脚本

Android Developer Console 屏幕截图被裁剪。还有谁有相同的问题吗?建议?

c# - 在 C# 中裁剪图像

C# 如何从 URL 获取服务器错误?

c# - 如何在 .NET ASP C# 中正确使用 QueryString?

python - 在 for 循环中更改脚本执行后

python - 使用线程池(使用 UWSGI)时 Flask 应用程序不工作

python - bytearray 的二进制反转值

user-interface - Unity3D - 特定 UI 元素的屏幕截图