2016-07-25 269 views
3

我使用Bokeh软件包生成地图以显示模拟结果。输出是具有交互性的html格式的单独地图。交互性是个别地图所必需的。Python打开html文件,截取屏幕截图,裁剪并保存为图像

请参阅此链接的示例:

http://bokeh.pydata.org/en/0.10.0/docs/gallery/texas.html

仿真可以被自动设置为运行的次数和将产生的地图为每次运行。这可能是100张地图。我希望能够将地图缝合在一起以创建电影 - 交互性不是必需的。 Bokeh具有通过浏览器创建PNG文件的功能,因此可以手动将每个地图保存为文件并使用ffmpeg创建电影。但是,如果您需要为100个文件执行此操作,则这不是一个真正的选项。目前无法通过Bokeh自动生成PNG文件,但我相信它会在某些时候添加。

所以我需要一个解决方法。我的想法是从他们存储在本地驱动器上的位置打开每个html文件,拍摄屏幕截图,裁剪图像以保留所需的部分并保存。但我还没有找到可行的解决方案。

裁剪图像很简单:

from PIL import Image 

img = Image.open(file_name) 
box = (1, 1, 1000, 1000) 
area = img.crop(box) 
area.save('saved_image', 'jpeg') 

我的问题是打开HTML文件,并采取截屏摆在首位喂到上面的代码。

为此,我尝试了以下操作,但都需要一个URL而不是html文件。也都使用Firefox不起作用,但我已经安装了Chrome并适当地更改了代码。

How to take partial screenshot with Selenium WebDriver in python?

http://www.idiotinside.com/2015/10/20/take-screenshot-selenium-python/

我的代码是:

from selenium import webdriver 

driver = webdriver.Chrome() 
driver.get('file_name') 
driver.save_screenshot('image.png') 
driver.quit() 

将返回:

{"code":-32603,"message":"Cannot navigate to invalid URL"} 

显然文件名不是一个URL,这样是明确的。如果你通过它的网站,它工作正常。任何帮助获得一个HTML加载和拍照将不胜感激!它不必涉及硒。

+0

是什么操作系统,你运行? – zhqiat

+0

Ubuntu 14.04和Windows。 – Pete

+0

我希望一个散景的人有一个方法给你;但我会建议使用Qt的qwebview渲染你的HTML,并抓住窗口形象http://stackoverflow.com/questions/24413385/pyqt4-qwidget-save-as-image – mdurant

回答

4

由于散景0.12.6的,现在无需打开浏览器更容易直接从Python中采取这些截图。

导出的PNG文件看起来像这样

export_png(plot, filename="plot.png") 

和出口SVGs看起来像这样

plot.output_backend = "svg" 
export_svgs(plot, filename="plot.svg") 

有迹象表明,需要安装一些可选的依赖。 你可以在Exporting Plots section of the User Guide找到更多的信息。

+0

海事组织这应该是新的接受的答案 – bigreddot

+0

同意和改变 – Pete

0

如果您正在运行Linux,则可能需要执行以下步骤。

首先在默认应用程序中通过command line打开html文件。你可能需要做点像

import os 

os.system('command to open html file') 

使用solution listed来截取你的截图。

然后按照建议在PIL中进行处理。

如果你在Windows这样做,

您可能要设置的AutoIt的驱动程序,以便您可以使用Python脚本来处理GUI窗口等。

2

您可以使用SimpleHTTPServer创建一个基本的Web服务器暴露你的本地文件。

你应该在HTMT是python -m SimpleHTTPServer 8000

然后,只需改变driver.get('file_name')driver.get('localhost:8000/file_name.html')

我建议你使用路径运行此“等到”,以确保一切都加载之前拿截图:

driver.wait.until(EC.visibility_of_element_located((By.XPATH,'//*[@id="someID"]')))

2

hgazibara意见被证明是最简单的˚F九。一些简化的代码在下面提供答案。如果网页实际上并不需要显示自己的屏幕截图,那将会很好。我会看看我是否可以稍后添加。

import glob 
from PIL import Image 
from selenium import webdriver 

# get a list of all the files to open 
glob_folder = os.path.join(file_location, '*.html') 

html_file_list = glob.glob(glob_folder) 
index = 1 

for html_file in html_file_list: 

    # get the name into the right format 
    temp_name = "file://" + html_file 

    # open in webpage 
    driver = webdriver.Chrome() 
    driver.get(temp_name) 
    save_name = '00' + str(index) + '.png'  
    driver.save_screenshot(save_path, save_name)) 
    driver.quit() 
    index += 1 

    # crop as required 
    img = Image.open(save_path, save_name)) 
    box = (1, 1, 1000, 1000) 
    area = img.crop(box) 
    area.save('cropped_image' + str(index), 'png')