2013-05-14 96 views
-1

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

从技术上讲,我想在程序中执行一个网页浏览器的东西..是否有可能?

我期待在Python环境

+2

也许[硒(https://pypi.python.org/pypi/selenium) – root 2013-05-14 06:29:41

+0

是硒的最佳解决方案,它有Python接口。 – specialscope 2013-05-14 06:49:11

+0

@specialscope您认为硒可以在云平台上运行吗?说,谷歌应用程序引擎,开放班等。(任何PaaS) – Iamcool 2013-05-14 10:42:54

回答

3

使用PySide或PyQt的,它的代码相当的几行:

UPDATE:固定码:

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

这似乎工作..但我有一个问题。在我的代码中,JS定义了页面的一些设计。并且它必须在脚本读取图像之前加载。 – Iamcool 2013-05-14 08:28:24

+0

加入'self.wait'不工作 – Iamcool 2013-05-14 09:03:01

+0

此外,这个脚本没有终止 – Iamcool 2013-05-14 09:03:46

1

正如已经建议,硒的webdriver的Python绑定可能有所帮助。您的代码可能是这样的:

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")