サーバレス練習帳

着眼大局着手小局

【python】IEからHTML全要素取得

≪動いているIEからエレメントを取得≫
まさかこんな簡単にできるとは。。。

import win32gui
import win32con
import pythoncom
import win32com.client

class clsIETabs(object):
	list = []
	def getIETabs(self):
		return self.list
	def getIETabsCount(self):
		return self.list
	def setIETab(self, value):
		self.list.append(value)

def checkIETab(hWnd,IETabs):
	if (win32gui.GetClassName(hWnd) == 'Internet Explorer_Server'):
		print(str(hWnd)+' : '+win32gui.GetClassName(hWnd)+' : '+win32gui.GetWindowText(hWnd))
		IETabs.setIETab(hWnd);

def main():
	IETabs = clsIETabs()
	win32gui.EnumChildWindows(win32gui.FindWindow(u"IEFrame",None),lambda hWnd, _: checkIETab(hWnd,IETabs), None)
	print(IETabs.getIETabs())
	msg = win32gui.RegisterWindowMessage("WM_HTML_GETOBJECT")
	for hIETab in IETabs.list :
		print(hIETab)
		ret,res = win32gui.SendMessageTimeout(hIETab, msg, 0, 0, win32con.SMTO_ABORTIFHUNG, 1000)
		#iDoc2 = pythoncom.ObjectFromLresult(res, 'IHTMLDocument2', 0)
		ob = pythoncom.ObjectFromLresult(res,pythoncom.IID_IDispatch,0)
		print(ob)
		doc = win32com.client.dynamic.Dispatch(ob)
		print(u"doc.url=",doc.url)
		print(u"doc.title=",doc.title)
		for docelement in doc.all :
			print('element : ',docelement,' id : ',docelement.id)

if __name__ == '__main__':
    main()

ちなみに、frameがある場合は、少し工夫が必要。
まぁ、frameがあっても取得できることは確認できました。
これ、私なりに快挙です!

### 抜粋 ###
for docElement in doc.all :
	print('tagName : ',docElement.tagName,'; id : ',docElement.innerText)
	if docElement.tagName == 'FRAME' :
		docFrame = win32com.client.dynamic.Dispatch(docElement.contentDocument)
		for docFrameElement in docFrame.all :
			print('[inside frame] tagName : ',docFrameElement.tagName,'; id : ',docFrameElement.id)


次を参考にしました。
fanblogs.jp

上記のサイトによると、ボタンも押せるらしいので、文字を書き込んだりすることも、恐らく可能でしょう。
最後に、Invokeできるか否かが重要だな。

≪イベント受信の参考≫
そして、イベント受信っぽいpythonを解説している・・・と思われるページを見つけた。あとで読もう。

◆4つのメソッドの検証
https://mail.python.org/pipermail/python-win32/2006-August/004979.html
⇒ スレッドと組み合わせたら、行けるのでは?

◆短めのスクリプト
https://mail.python.org/pipermail/python-list/2005-May/323208.html


[python-win32] Processing IE DOM events.



http://code.activestate.com/lists/python-list/455354/


https://mail.python.org/pipermail/python-list/2002-November/172693.html


≪PyDispatchの説明≫
リファレンスか?
http://timgolden.me.uk/pywin32-docs/PyIDispatch.html

この本も参考になるか?
books.google.co.jp
そして、この本は無料で全て読めそう。
manualzz.com