wxpython使用IEHtmlWindow控制DOM树

wxpython使用IEHtmlWindow控制DOM树

在wxpython里面有几种方法来内嵌ie浏览器,因为不是这文章的主要内容就不做具体的介绍了

本文章里面使用的是wx.lib.iewin.IEHtmlWindow 不清楚为什么官方文档里面没有对这个东西的API有介绍,最好的方法是你打开源文件来查看里面的函数,查看过源代码后知道了DOM树的获取是wx.lib.iewin.IEHtmlWindow.ctrl.Document

在拥有了DOM树后就不由自主的想可以更改Document.getElementById("email").value = "sdf"得到的是一个不可以更改的异常

久经查质料发现了http://ginstrom.com/scribbles/2010/12/19/setting-contenteditable-in-a-wxpython-iehtmlwindow/这文章,文章里面把查找到的DOM树包装了一下,完后更改了某个元素是否能更改的属性,代码如下

import wx
from wx.lib import iewin
from comtypes.gen import MSHTML

class MyFrame(wx.Frame):
    def __init__(self):
        """Init IEHtmlWindow and set ourselves as event sink"""
        wx.Frame.__init__(self, None, title="IEHtmlWindow")
        self.ie = iewin.IEHtmlWindow(self)
        self.ie.AddEventSink(self)
        self.ie.Navigate("http://example.com/") # your URL here

    def DocumentComplete(self, this, pDisp, URL):
        """
        Called when the HTML document finishes loading.
        If we were waiting on any actions to perform
        when the document was complete, we execute them here.
        """
        element = self.ie.ctrl.Document.getElementById("my_element")
        element3 = element.QueryInterface(MSHTML.IHTMLElement3)
        element3.contentEditable = "true"

app = wx.App(False)
MyFrame().Show()

app.MainLoop()

经过查阅MSDN发现MSHTML提供了无数的接口来对DOM进行操控,而上面文章中介绍的用了IHTMLElement3这个接口,这个接口并没有我们需要的一些函数,比如说对文本的更改,对按钮的点击等,寻找到IHTMLElement这个接口中拥有了许多我们需要的元素。

那么一个获得DOM元素更改其内容的代码如下;

        element = self.ie.ctrl.Document.getElementById("my_element")
        element3 = element.QueryInterface(MSHTML.IHTMLElement)
        element3.innerText = "hello"

如果是想点击某个按钮的话:

        element = self.ie.ctrl.Document.getElementById("login")

        element3 = element.QueryInterface(MSHTML.IHTMLElement)

        element3.click()

对于IE的接口的描述文章:http://msdn.microsoft.com/en-us/library/aa703950(v=VS.85).aspx

你可能感兴趣的:(wxpython使用IEHtmlWindow控制DOM树)