1

我想使用 gtk 和 webkit 加载和显示一个 html 页面。这是我到目前为止所做的:

加载一个 html 页面,更改其外观(通过 JAVASCRIPT)并使用 WEBKIT 在 PYGTK GUI 中显示它

问题是我想通过去掉一些 div 来自定义这个页面的外观。

有人可以指出我正确的方向。

谢谢法布里齐奥

4

1 回答 1

1

我会回答我自己的问题。

这个问题的解决方案实际上是在这里提出的,可以通过使用 webkit 方法execute_script和代码(未经测试和不完整的代码):

import gtk
import webkit

def load_finished(b):
    js = 'alert("a");'
    b.execute_script(js)


w = gtk.Window()
b = webkit.WebView()
w.add(b)
b.open('http://example.com')
w.show_all()

b.connect("load-finished", load_finished)

gtk.main() 

此处提供了完整的解决方案(也是我实施的解决方案):

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import gtk, webkit
# import jswebkit

# set of methods for the browser
def delete_event(widget, event, data=None):
    return False

def destroy(widget, data=None):
    gtk.main_quit()

def go_back(widget, data=None):
    browser.go_back()

def go_forward(widget, data=None):
    browser.go_forward()

def go_home(widget, data=None):
    browser.open("http://opencores.org/projects")

def load_www(widge, url):
    try:
        url.index("://")
    except:
        url = "http://" + url
    www_adr_bar.set_text(url)
    browser.open(url)

def load_www_bar(widge):    
    url = www_adr_bar.get_text()
    load_www(widge, url)

def update_buttons(widget, data=None):
    www_adr_bar.set_text( widget.get_main_frame().get_uri() )
    back_button.set_sensitive(browser.can_go_back())
    forward_button.set_sensitive(browser.can_go_forward())

def load_progress_amount(webview, amount):
    progress.set_fraction(amount/100.0)

    js_code = """
        var el1 = document.getElementsByClassName("top")[0]; 
        if (el1) el1.parentNode.removeChild(el1);

        var el2 = document.getElementsByClassName("banner")[0]; 
        if (el2) el2.parentNode.removeChild(el2);

        var el3 = document.getElementsByClassName("line")[0]; 
        if (el3) el3.parentNode.removeChild(el3);

        var el4 = document.getElementsByClassName("lang")[0]; 
        if (el4) el4.parentNode.removeChild(el4);

        var el5 = document.getElementsByClassName("mainmenu")[0]; 
        if (el5) el5.parentNode.removeChild(el5);

        var el6 = document.getElementsByClassName("pad_leftside")[0]; 
        if (el6) el6.parentNode.removeChild(el6);

        var el7 = document.getElementsByClassName("menu-tools")[0]; 
        if (el7) el7.parentNode.removeChild(el7);

        var el8 = document.getElementsByClassName("content")[0];
        if (el8){ var el81 = el8.nextElementSibling
                  if (el81 != null) el81.parentNode.removeChild(el81); }

        d1 = document.getElementsByClassName('main')[0];
        if(d1){d1.style.width="100%";
               d1.style.margin="0pt";}

        d2 = document.getElementsByTagName('body')[0];
        if(d2) d2.style.backgroundColor= "#FFF";

        d3 = document.getElementsByClassName('content')[0];
        if (d3) {d3.style.width="100%";
                 d3.style.paddingBottom ="20pt";}

        function getsupportedprop(proparray){
            var root=document.documentElement
            for (var i=0; i<proparray.length; i++){
                if (typeof root.style[proparray[i]]=="string"){
                    return proparray[i] 
        }}}

        // change some css3 proprieties 
        var boxshadowprop=getsupportedprop(['boxShadow', 'MozBoxShadow', 'WebkitBoxShadow'])
        d4 = document.getElementsByClassName('main')[0];
        if(d4) d4.style[boxshadowprop]='0px 0px 0px #FFF';
    """
    try:
        pass
        webview.execute_script(js_code)
        #ctx = get_js_context(webview)
        #ctx.EvaluateScript(js_code)
    except:
        pass

def load_started(webview, frame):
    progress.set_visible(True)

#def get_js_context(webview):
#    frame = webview.get_main_frame()
#    return jswebkit.JSContext(frame.get_global_context())

def load_finished(webview, frame):
    progress.set_visible(False)

def download(webview, download):

    import threading, urllib

    saveas = gtk.FileChooserDialog(title=None,
             action=gtk.FILE_CHOOSER_ACTION_SAVE,
             buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                      gtk.STOCK_SAVE, gtk.RESPONSE_OK))

    # get url under the mouse and propose it as file name
    downloadfrom = download.get_network_request().get_uri()
    saveas.set_current_name(downloadfrom.split('/')[-1]) # better stripping method is needed

    saveas.set_default_response(gtk.RESPONSE_OK)
    resp = saveas.run()

    if resp == gtk.RESPONSE_OK:
        downloadto = saveas.get_filename()
    saveas.destroy()

    if resp == gtk.RESPONSE_OK:
        # TODO this needs to go in a different thread
        # also, this will not work with the link: http://opencores.org/download,audio
        print 'Downloading: ', downloadfrom, 'and saving it in:', downloadto

        #urllib.urlretrieve(downloadfrom, downloadto)

        # multithreading version
        mythread = threading.Thread(target = urllib.urlretrieve,
                                   args = (downloadfrom,downloadto))
        mythread.start()


if __name__ == '__main__':
    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.set_size_request(920, 600)
    win.connect("delete_event", delete_event)
    win.connect("destroy", destroy)
    win.set_resizable(True)

    scroller = gtk.ScrolledWindow()
    browser = webkit.WebView()

    settings = browser.get_settings()
    settings.set_property('enable-default-context-menu', True)


    browser.connect("load-progress-changed", load_progress_amount)
    browser.connect("load-started", load_started)
    browser.connect("load-finished", load_finished)
    browser.connect("load_committed", update_buttons)
    #browser.connect("download-requested", download_link)
    browser.connect("download_requested", download)

    prj_button = gtk.Button('OpenCores')
    login_button = gtk.Button('Login')
    account_button = gtk.Button('My Account')
    faq_button = gtk.Button('FAQ')

    prj_button.connect("clicked", load_www,'http://opencores.org/projects')
    login_button.connect("clicked", load_www,'http://opencores.org/login')
    account_button.connect("clicked", load_www,'http://opencores.org/acc')
    faq_button.connect("clicked", load_www,'http://opencores.org/faq')

    www_adr_bar = gtk.Entry()
    www_adr_bar.connect("activate", load_www_bar)
    hlp_hbox = gtk.HBox()
    hlp_vbox = gtk.VBox()
    progress = gtk.ProgressBar()
    back_button = gtk.ToolButton(gtk.STOCK_GO_BACK)
    back_button.connect("clicked", go_back)
    forward_button = gtk.ToolButton(gtk.STOCK_GO_FORWARD)
    forward_button.connect("clicked", go_forward)
    #home_button = gtk.ToolButton(gtk.STOCK_HOME)
    #home_button.connect("clicked", go_home)

    # put stuff together
    hlp_hbox.pack_start(back_button,False, False,5)
    hlp_hbox.pack_start(forward_button,False, False)
    #hlp_hbox.pack_start(home_button,False, False)

    hlp_hbox.pack_start(prj_button,False, False,4)
    hlp_hbox.pack_start(login_button,False, False,4)
    hlp_hbox.pack_start(account_button,False, False,4)
    hlp_hbox.pack_start(faq_button,False, False,4)

    hlp_hbox.pack_start(www_adr_bar,True, True,4)

    hlp_vbox.pack_start(hlp_hbox,False, False,2)
    hlp_vbox.pack_start(scroller,True, True,4)
    hlp_vbox.pack_start(progress,False, False)
    scroller.add(browser)

    default_www = 'http://opencores.org/projects'
    www_adr_bar.set_text(default_www)

    # LOAD PAGE
    browser.open(default_www)
    back_button.set_sensitive(False)
    forward_button.set_sensitive(False)

    win.add(hlp_vbox)
    win.show_all()
    gtk.main()

这将产生以下结果:

在此处输入图像描述

如果没有命令webview.execute_script(js_code),效果将是:

在此处输入图像描述

于 2012-08-02T09:23:26.980 回答