Python操作IHTMLDocument2用于自动化测试
有些软件的界面采用Win32窗口嵌套一个IE控件,用Spy++只能识别出一个Internet Explorer_Server控件。常用的几个API函数无法取到IE控件里面的内容,更无法对里面的控件进行操作,所以这给自动化带来了麻烦。本文将讲述如何使用Python获取IHTMLDocument2接口,用于自动化测试。
相应的Python实现代码如下:
获取IHTMLDocument2接口
参考:http://support.microsoft.com/kb/249232相应的Python实现代码如下:
#!/usr/bin/env python
#coding:utf-8
__author__ = 'CoderZh'
import sys
# Important for multithreading
sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED
import win32com
import win32com.client
import win32gui
import win32con
import pythoncom
def getIEServer(hwnd, ieServer):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
ieServer.append(hwnd)
if __name__ == '__main__':
#pythoncom.CoInitializeEx(0) # not use this for multithreading
mainHwnd = win32gui.FindWindow('windowclass', 'windowtitle')
if mainHwnd:
ieServers = []
win32gui.EnumChildWindows(mainHwnd, getIEServer, ieServers)
if len(ieServers) > 0:
ieServer = ieServers[0]
msg = win32gui.RegisterWindowMessage('WM_HTML_GETOBJECT')
ret, result = win32gui.SendMessageTimeout(ieServer, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
doc = win32com.client.dynamic.Dispatch(ob)
print doc.url
doc.all['id'].click()
#pythoncom.CoUninitialize()
#coding:utf-8
__author__ = 'CoderZh'
import sys
# Important for multithreading
sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED
import win32com
import win32com.client
import win32gui
import win32con
import pythoncom
def getIEServer(hwnd, ieServer):
if win32gui.GetClassName(hwnd) == 'Internet Explorer_Server':
ieServer.append(hwnd)
if __name__ == '__main__':
#pythoncom.CoInitializeEx(0) # not use this for multithreading
mainHwnd = win32gui.FindWindow('windowclass', 'windowtitle')
if mainHwnd:
ieServers = []
win32gui.EnumChildWindows(mainHwnd, getIEServer, ieServers)
if len(ieServers) > 0:
ieServer = ieServers[0]
msg = win32gui.RegisterWindowMessage('WM_HTML_GETOBJECT')
ret, result = win32gui.SendMessageTimeout(ieServer, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
ob = pythoncom.ObjectFromLresult(result, pythoncom.IID_IDispatch, 0)
doc = win32com.client.dynamic.Dispatch(ob)
print doc.url
doc.all['id'].click()
#pythoncom.CoUninitialize()
多线程操作
IHTMLDocument2是线程安全的,默认情况下不能在多线程中使用,否则会抛异常。但是在具体使用过程中,又必须使用多线程。解决办法就是上面的代码中的:
# Important for multithreading
sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED
sys.coinit_flags = 0 # pythoncom.COINIT_MULTITHREADED
这句必须在开头的时候设定,同时,不要再显示调用pythoncom.CoInitializeEx(0)和 pythoncom.CoUninitialize()。
参考:http://bytes.com/topic/python/answers/26897-multithreaded-com-server-problem
IHTMLDocument2 接口
IHTMLDocument2接口有哪些方法,可以查询http://msdn.microsoft.com/en-us/library/aa752574%28VS.85%29.aspx
基本能够满足自动化测试的需要,可以在此基础上封装出更易使用的自动化UI测试框架。
技术改变世界!
--狂诗绝剑