如何在Python + Webkit + Gtk中下载文件浏览器? [英] How to download a file browser in Python+Webkit+Gtk?

查看:202
本文介绍了如何在Python + Webkit + Gtk中下载文件浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Python Webkit Gtk中的简单浏览器:

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

浏览效果很好。不幸的是,在本地计算机上保存文件不起作用。我找不到准备好的解决方案。我不需要进度条,文件夹选择,我想点击链接导致下载。你知道将文件保存到目录/ home / user的最简单的方法吗?

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?

推荐答案

正如在 docs ,你有连接到 mime-type-policy-decision-requested-requests-requested 下载请求信号。

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)

然后,您检查mime类型,并决定是否要下载:

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

下载请求之后,您可以让 WebKit.Download 对象处理下载或(在这种情况下)使用python:

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

这篇关于如何在Python + Webkit + Gtk中下载文件浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆