在wxpython裡面有幾種方法來内嵌ie浏覽器,因為不是這文章的主要内容就不做具體的介紹了
本文章裡面使用的是wx.lib.iewin.IEHtmlWindow 不清楚為什麼官方文檔裡面沒有對這個東西的API有介紹,最好的方法是你打開源檔案來檢視裡面的函數,檢視過源代碼後知道了DOM樹的擷取是wx.lib.iewin.IEHtmlWindow.ctrl.Document
在擁有了DOM樹後就不由自主的想可以更改Document.getElementById("email").value = "sdf"得到的是一個不可以更改的異常
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()