我有一些HTML代码作为字符串数据。现在,我需要以编程方式呈现代码,使用特定元素的大小截取屏幕截图!!
从技术上讲,我想在程序中执行Web浏览器..是否可能?
我正在寻找Python环境
答案 0 :(得分: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_()
答案 1 :(得分: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")