0

我有一些 html 代码作为字符串数据。现在,我需要以编程方式渲染代码,截取特定元素大小的屏幕截图!!

从技术上讲,我想在程序中执行网络浏览器的事情.. 有可能吗?

我正在寻找 Python 环境

4

2 回答 2

3

使用 PySide 或 PyQT,只需几行代码:

更新:固定代码:

from PySide.QtCore import QUrl, QTimer
from PySide.QtGui import QApplication, QImage, QPainter
from PySide.QtWebKit import QWebView


class Browser(QWebView):

    def __init__(self, app):
        QWebView.__init__(self)
        self.parent_app = app
        self.loadFinished.connect(self._load_finished)
        self.wait = 5 * 1000  # 5 secs

    def _load_finished(self, ok):
        if self.wait:
            QTimer.singleShot(self.wait, lambda: self._load_finished(ok))
            self.wait = None
            return

        frame = self.page().mainFrame()
        self.page().setViewportSize(frame.contentsSize())
        image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
        painter = QPainter(image)
        frame.render(painter)
        painter.end()
        image.save('test.png')

        self.close()
        self.parent_app.quit()

    def open(self, url):
        self.load(QUrl(url))


if __name__ == '__main__':
    app = QApplication([])
    html = """
    <html>
        <head>
            <script type="text/javascript">
                setTimeout(function () {
                    var e = document.getElementById("later");
                    e.innerHTML = "arrived";
                }, 2500);
            </script>
        </head>
        <body>
            <div id="later"></div>
            <div style="margin: 0 auto; width: 500px;">
                <img src="http://www.caminodesantiago.me/wp-content/uploads/water-bottle.jpg" />
            </div>
        </body>
    </html>
    """
    browser = Browser(app)
    browser.setHtml(html)
    app.exec_()
于 2013-05-14T06:47:07.077 回答
2

正如已经建议的那样,Selenium Webdriver Python Bindings 可以提供帮助。您的代码可能如下所示:

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

browserHandler = webdriver.Firefox()
browserHandler.get(yourUrl)
try:
    browserHandler.get_screenshot_as_file(yourPathToNewImage)
except WebDriverException:
    print("WebDriverException caught while trying to get a screenshot")
于 2013-05-14T07:20:32.470 回答