首页 > 代码库 > COM-IE-(2)

COM-IE-(2)

# -*- coding:UTF-8 -*- 
import sys
from time import sleep
import win32com.client
from win32com.client import DispatchEx

stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
reload(sys)
sys.setdefaultencoding("utf-8")
sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr

class COM_IE:
	def __init__(self,url=None):
		self.url = url
		self.Visible = 1
		self.ie = self.openIE(url)
		self.document = ""
		self.text = ""
		self.charset = None

	def ExistIE(self,url):
		ShellWindowsCLSID = '{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
		ies=DispatchEx(ShellWindowsCLSID)
		if len(ies)==0:
			return None
		for ie in ies:
			if ie.LocationURL==url:
				return ie
		return None
		
	def NewIE(self,url):
		ie = DispatchEx("InternetExplorer.Application")
		ie.Visible = self.Visible
		ie.Navigate(url)
		return ie
		
	def openIE(self,url):
		ie = self.ExistIE(url)
		if ie==None:
			ie = self.NewIE(url)
		return ie
		
	def WaitIE(self):
		# while self.ie.Busy:
			# leep(1)
		while 1:    
			state = self.ie.ReadyState    
			if state ==4: 
				# print "load done..."
				self.charset  = self.ie.Document.charset
				self.document = self.ie.Document.body.innerHTML
				self.text = self.ie.Document.body.innerText 
				break    
			sleep(1)
			
	def Visible(self):
		self.ie.Visible = self.Visible
		
	def GetBody(self):
		self.WaitIE()
		return self.ie.Document.body
		
	def GetNodes(self,parentNode,tag):
		"""
		>>> coldiv=GetNodes(body,"div")
		"""
		childNodes=[]
		for childNode in parentNode.getElementsByTagName(tag):
			childNodes.append(childNode)
		return childNodes
		
	def NodeByAttr(self,Nodes,nodeattr,nodeval):
		"""
		>>> div_id_editor=NodeByAttr(coldiv,"id","editor_ifr")
		"""
		for node in Nodes:
			if str(node.getAttribute(nodeattr))==nodeval:
				return node
		return None

	def SetNodeHtml(self,body,node_type,node_attr,node_attr_val,node_inner_html):
		tags = self.GetNodes(body,node_type)
		node = self.NodeByAttr(tags,node_attr,node_attr_val)
		node.innerHTML = node_inner_html
			
	
	def SetNodeVal(self,body,node_type,node_attr,node_attr_val,node_value):
		tags = self.GetNodes(body,node_type)
		node = self.NodeByAttr(tags,node_attr,node_attr_val)
		node.value = http://www.mamicode.com/node_value>

COM-IE-(2)