How to download a file browser in Python+Webkit+Gtk?

匆匆过客 提交于 2019-12-13 08:10:11

问题


Here is a simple browser in Python Webkit Gtk:

#!/usr/bin/python

import gtk
import webkit

view = webkit.WebView()
sw = gtk.ScrolledWindow()

sw.add(view)

win = gtk.Window(gtk.WINDOW_TOPLEVEL)

win.add(sw)

win.show_all()

view.open("https://www.kernel.org/")

gtk.main()

Browsing works perfectly. Unfortunately, it does not work to save files on the local computer. I could not find a ready solution. I do not need a progress bar, folder selection, I want to click on the link resulted in downloading. Do you know the easiest way to save files to the directory /home/user?


回答1:


As it says in the docs, you have to connect to the mime-type-policy-decision-requested and download-requested signals.

view.connect('download-requested', download_requested)
view.connect('mime-type-policy-decision-requested', policy_decision_requested)

Then you check the mime-type and decide if you want to download it:

def policy_decision_requested(view, frame, request, mimetype, policy_decision):
    if mimetype != 'text/html':
        policy_decision.download()
        return True

When download-requested is emitted afterwards, you can let the WebKit.Download object handle the download or (in this case) do it with python:

def download_requested(view, download):
    name = download.get_suggested_filename()
    path = os.path.join(
        GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_DOWNLOAD),
        name
    )
    urlretrieve(download.get_uri(), path)  # urllib.request.urlretrieve
    return False


来源:https://stackoverflow.com/questions/41503714/how-to-download-a-file-browser-in-pythonwebkitgtk

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