( endi123 | 2020. 02. 22., szo - 01:40 )

Szerkesztve: 2020. 02. 22., szo - 02:03

bongeszo-kepmento.py

Usage:   bongeszo-kepmento.py src_url dst_png_path render_width
Example: bongeszo-kepmento.py https://hup.hu hup-mentes.png 1200

További beállítások a programon belül: "headless" és "snapshot_opts"

Ha headless=True és a webkit-nek nem tetsző, nem komplett URI-t adtál, akkor "kill bongeszo-kepmento.py". (headless=False esetén elég Alt+F4 a megnyíló ablakon)

Telepítendő csomagok (Ubuntu 18.04.mai elnevezések):

  • python3-gi
  • gir1.2-webkit2-4.0
  • libwebkit2gtk-4.0-37  (ezt Ubuntu-n behúzza a előző, talán más rendszeren nem)
#!/usr/bin/env python3

import sys
print("Python executable:", sys.executable)
print("Python version:   ", sys.version.replace('\n', ' '))

import os
print("Python venv:      ", end=' ')
try:
    print(os.environ['VIRTUAL_ENV'])
except:
    print("not in venv")

print("Python path:      ", *sys.path, sep = '\n\t')


import gi
print("Module gi path:   ", gi.__file__)

gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk, Gdk, WebKit2

ctx = WebKit2.WebContext()

# Command line arguments
if 4 != len(sys.argv):
    print("Usage:   bongeszo-kepmento.py src_uri dst_png_path render_width")
    print("Example: bongeszo-kepmento.py https://hup.hu hup-mentes.png 1200")
    exit(-1)
src_uri = sys.argv[1]
dst_png_path = sys.argv[2]
render_width = int(sys.argv[3])

# Tweak "headless" and "snapshot_opts" as you like
headless = False
if headless:
    base = Gtk.OffscreenWindow
else:
    base = Gtk.Window

snapshot_opts = WebKit2.SnapshotOptions.TRANSPARENT_BACKGROUND
#snapshot_opts = WebKit2.SnapshotOptions.NONE


class Browser(base):
    def __init__(self, uri):
        super(Browser, self).__init__()
        
        self.webview = WebKit2.WebView.new_with_context(ctx)
        self.webview.connect("load-changed", self.on_load_changed)
        self.webview.load_uri(uri)
        self.add(self.webview)

        self.connect("destroy", Gtk.main_quit)
        self.set_size_request(render_width, 600) # set minimum size allowed

        self.set_title("Bongeszo - " + uri)
        self.show_all()
    
    
    # WebView events
    
    def on_load_changed(self, web_view, load_state):
        print("Load-state:", load_state)
        if load_state == WebKit2.LoadEvent.FINISHED:
            print("Taking snapshot ...")
            web_view.get_snapshot(WebKit2.SnapshotRegion.FULL_DOCUMENT, snapshot_opts, cancellable=None, callback=self.on_snapshot_finish)
    
    def on_snapshot_finish(self, web_view, result):
        print("Snapshot ready")
        cairo_surf = web_view.get_snapshot_finish(result)
        cairo_surf.write_to_png(dst_png_path)
        print("Snapshot saved to", dst_png_path)
        self.close()
        
if __name__ == "__main__":
    Gtk.init(sys.argv)
    Browser(src_uri)
    Gtk.main()