0

我试图处理 webview resource_load_started 和 webresource finished 信号以获取响应正文,但遇到了麻烦。

这是我的python代码:

import gi

gi.require_version('WebKit2', '4.0')
gi.require_version("Gtk", "3.0")

from gi.repository import WebKit2, Gtk

window = Gtk.Window()
window.connect('delete-event', Gtk.main_quit)

view = WebKit2.WebView()
view.load_uri('https://yandex.com/')

def resorce_load_finished(resource):
    raw_data = resource.get_data(cancellable=None, callback=None, user_data=None)
    print("url: ", resource.get_response().get_uri(), "data_length: ", resource.get_response().get_content_length(), "\r\nraw_data: ", raw_data)

def resorce_load_started(view, resource, request):
    resource.connect("finished", resorce_load_finished)

view.connect("resource_load_started", resorce_load_started)

window.add(view)
window.set_default_size(1024,1024)
window.show_all()

Gtk.main()

输出如下(去掉了 https 前缀):

/home/again/Documents/webkit2/venv/bin/python /home/again/Documents/webkit2/get_resource.py
url:  //lazka.github.io/pgi-docs/#WebKit2-4.0 data_length:  1842 
raw_data:  None
url:  //lazka.github.io/pgi-docs/sidebar.html data_length:  6344 
raw_data:  None
url:  //lazka.github.io/pgi-docs/WebKit2-4.0/ data_length:  2216 
raw_data:  None
url:  //lazka.github.io/pgi-docs/js.cookie-2.1.0.min.js data_length:  874 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/css/pgi.css data_length:  1047 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/graphviz.css data_length:  215 
raw_data:  None
url:  //lazka.github.io/pgi-docs/pgi-config.js data_length:  388 
raw_data:  None
url:  //lazka.github.io/pgi-docs/pgi-searchtools.js data_length:  2973 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/css/theme.css data_length:  19061 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/fonts/lato-bold.ttf data_length:  39816 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/fonts/fontawesome-webfont.ttf data_length:  83998 
raw_data:  None
url:  //lazka.github.io/pgi-docs/_static/fonts/lato-regular.ttf data_length:  39653 
raw_data:  None

Process finished with exit code 0

我的问题是我使用正确的信号处理程序吗?如果使用正确,那么,为什么resource.get_data()总是返回 None,那里会发生什么?我只能获取响应 URL 及其长度。

4

1 回答 1

0

必须调用get_data_finish才能获得最终结果。像这样的东西:

def res_finished(resource, result, error):
    data = resource.get_data_finish(result)
    print(resource.get_uri(), data)

def received_data(resource, data_length):
    resource.get_data(cancellable=None, callback=res_finished, user_data=None)

def resource_load_started(view, resource, request):
    resource.connect("received_data", received_data)

view.connect("resource_load_started", resource_load_started)
于 2020-06-20T15:49:45.017 回答