整理了下,比如叫做 ie.py :
# -*- coding:utf-8 -*-
import time
from win32com.client import DispatchEx
def ExistIE(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(url):
ie=DispatchEx("InternetExplorer.Application")
ie.Navigate(url)
return ie
def openIE(url):
"""
>>> myie = ie.NewIE()
"""
ie=ExistIE(url)
if ie==None:
ie=NewIE(url)
return ie
def WaitIE(ie):
while ie.Busy:
time.sleep(1)
def Visible(ie):
ie.Visible=1-ie.Visible
def GetBody(ie):
WaitIE(ie)
return ie.Document.body
def GetNodes(parentNode,tag):
"""
>>> coldiv=GetNodes(body,"div")
"""
childNodes=[]
for childNode in parentNode.getElementsByTagName(tag):
childNodes.append(childNode)
return childNodes
def NodeByAttr(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 SetNode(node,val):
node.innerHTML=val
if __name__=="__main__":
url="about:blank"
myie=NewIE(url)
Visible(myie)
mybody=GetBody(myie)
SetNode(mybody,"<div>Genius</div>"*3)
coldiv=GetNodes(mybody,"div")
SetNode(coldiv[0],"<p>Hello</p>"*10)
coldiv[0].SetAttribute("id","test")
div_id_test=ie.NodeByAttr(coldiv,"id","test")
div_p=GetNodes(div_id_test,"p")
for div_per_p in div_p:
print div_per_p.innerHTML
比如再去调用这个来登陆人人网:
# -*- coding:utf -*-
import getpass
import ie
url="http://renren.com/"
myie=ie.NewIE(url)
ie.Visible(myie)
mybody=ie.GetBody(myie)
input_ids=ie.GetNodes(mybody,"input")
input_id_email=ie.NodeByAttr(input_ids,"id","email")
input_id_email.value="yours@email.com"
input_id_psd=ie.NodeByAttr(input_ids,"id","password")
input_id_psd.value=getpass.getpass()
input_id_login=ie.NodeByAttr(input_ids,"id","login")
input_id_login.click()