Python open html file, take screenshot, crop and save as image

情到浓时终转凉″ 提交于 2019-12-05 11:15:29
Optional Argument

As of Bokeh 0.12.6, it is now easier to take those screenshots directly from Python without needing to open a browser.

Exporting PNGs looks like this

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

And exporting SVGs looks like this

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

There are some optional dependencies that need to be installed. You can find more information in the Exporting Plots section of the User Guide.

hgazibara comment proved to be the simplest fix. Some simplified code is below to provide the answer. It would be nice if the web page didn't actually have to show itself for the screen shot to be taken. I will see if I can add this later.

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

You can use SimpleHTTPServer to create a basic webserver and expose your local file.

You should run this in the path where the html is python -m SimpleHTTPServer 8000

Then just change driver.get('file_name') to driver.get('localhost:8000/file_name.html')

I recommend you to use "wait until" to be sure everything is loaded before take the screenshot:

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

zhqiat

If you're running Linux, you may have to do the following steps.

First open the html file via command line in the default app. You'll probably have to do something like

import os

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

Use the solution listed to take your screenshot.

Then do the processing in PIL as suggested.

If you're doing this in windows,

You may want to setup the AutoIT drivers so that you can use your python script to manipulate GUI windows etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!