python用win32com模拟浏览器(pam也是一样的原理)

 # -*- coding:UTF-8 -*- 
#!/user/bin/env python

import win32com.client
from time import sleep
 
loginurl='http://passport.cnblogs.com/login.aspx'
loginouturl='http://passport.cnblogs.com/logout.aspx'
username='XXX'
password='XXX'
 
ie = win32com.client.Dispatch("InternetExplorer.Application")    
ie.Visible = 0
 
 
ie.Navigate(loginurl)    
state = ie.ReadyState    
print "打开登陆页面"    
while 1:    
    state = ie.ReadyState    
    if state ==4:    
        break    
    sleep(1)
print "页面载入完毕,输入用户名密码"    
state = None
 
ie.Document.getElementById("tbUserName").value=username    
ie.Document.getElementById("tbPassword").value=password    
ie.Document.getElementById("btnLogin").click()   
 
 
while 1:    
    state = ie.ReadyState    
    print state    
    if state ==4 and str(ie.LocationURL) == "http://home.cnblogs.com/":    
        break
    sleep(1)
print "登陆成功" 
print '你的昵称是:'
print ie.Document.getElementById('lnk_current_user').title
 
#博客园只能登录一次,注销
print '注销!'
ie.Navigate(loginouturl)

还有一个是利用同样组件时间google搜索的:

#!/user/bin/env python
# -*- coding: cp936 -*-
import time
from win32com.client import Dispatch
urlFileName = "urlFile.txt"
outputFileName = "result.txt"
outputFile = open(outputFileName, 'w')
ie = Dispatch("InternetExplorer.Application")
ie.visible = 1
ie.navigate('http://www.google.com.hk')
while (ie.ReadyState != 4):
    time.sleep(1)
print 'Ò³ÃæÔØÈëÍê½á'
with open(urlFileName) as urlFile:
    for url in urlFile:
        url = url.strip()
        ie.Document.forms[0].elements["q"].value="site:" + url
        ie.Document.forms[0].submit()
        
        while (ie.ReadyState != 4 or str(ie.LocationURL).find(url) == -1):
            print str(ie.LocationURL)
            time.sleep(1)
        result = ie.Document.getElementById("ires").innerHTML
        if len(result)>0:
            print url, "recored"
            outputFile.write(url + ":recored/n")
        else:
            print url, "not recored"
            outputFile.write(url + ":not recored/n")
outputFile.close()


你可能感兴趣的:(python,浏览器,IE,Google,url,import)