【问题标题】:Cefpython GetText() functionCefpython GetText() 函数
【发布时间】:2018-01-18 09:19:53
【问题描述】:

大家好,我正在尝试将 url 的 html 打印到控制台。我从open source 中免费获取了 tutorial.py 中的代码。 那就是类:

class LoadHandler(object):
    def OnLoadingStateChange(self, browser, is_loading, **_):
        """Called when the loading state has changed."""
        if not is_loading:
            # Loading is complete. DOM is ready.
            # js_print(browser, "Python", "OnLoadingStateChange", "Loading is complete")
            print('ready')
            print(browser.GetMainFrame().GetText())

我添加了最后两行:

print('ready')
print(browser.GetMainFrame().GetText())

当我运行代码时,我得到一个错误消息:

TypeError: GetText() 只接受一个参数(给定 0)

我在文档中看到我需要给函数参数StringVisitor (https://github.com/cztomczak/cefpython/blob/master/api/Frame.md#gettext)

StringVisitor 是什么,我该如何解决这个问题?

【问题讨论】:

    标签: python python-3.x chromium cefpython


    【解决方案1】:

    StringVisitor 是实现Visit() 方法的类的对象。下面是你想要做的:

    class Visitor(object)
        def Visit(self, value):
            print(value)
    myvisitor = Visitor()
    class LoadHandler(object):
        def OnLoadingStateChange(self, browser, is_loading, **_):
            """Called when the loading state has changed."""
            if not is_loading:
                # Loading is complete. DOM is ready.
                print('ready')
                browser.GetMainFrame().GetText(myvisitor)
    

    myvisitor 放在OnLoadingStateChange() 函数之外看起来很奇怪,但这是在GetText() 函数返回后使该对象保持活动状态的众多方法之一,因为GetText() 是异步的。

    您需要在cefpython 中使用StringVisitor,因为许多CEF 函数是异步的,即在没有完成您希望它们执行的操作的情况下立即返回。当实际工作完成时,他们会调用您的回调函数。在您的示例中,当 GetText() 准备的文本准备好时,它将调用您的 StringVisitor 对象中的 Visit() 方法。这也意味着您需要在程序流程中换一种思路。

    (我在Need to get HTML source as string CEFPython回答了类似的问题)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多