python一个带验证码登录的实例

来源:互联网 发布:博途软件 编辑:程序博客网 时间:2024/05/16 15:24


import cookielib
import urllib
import urllib2
import re
from ghost import Ghost
import sys
import webbrowser
import os
import imghdr

IP = '127.0.0.1'
PORT = '8080'

MAIN_INDEX_URL  = 'http://'+IP+':'+PORT+'/testRon/login/logon.jsp'

LOGIN_URL = 'http://'+IP+':'+PORT+'/testRon/LoginServlet'

GETDATA_URL = 'http://'+IP+':'+PORT+'/testRon/login/getdata.jsp'

GETDATA_CLICK_URL = 'http://'+IP+':'+PORT+'/testRon/login/getdataclick.jsp'

IMAGE_URL = 'http://'+IP+':'+PORT+'/testRon/imageServlet'


class UserAction(object):
 
    def __init__(self, username, password):
        self.username = username
        self.password = password
     
        self.cj = cookielib.LWPCookieJar()
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))

     
        urllib2.install_opener(opener)
  
    def login(self): 

        req = urllib2.Request(IMAGE_URL)

        page1=urllib2.urlopen(req)
        my_picture = page1.read()


        filename = imghdr.what("",my_picture)
        print filename

        filename = "my_image."+filename

        print filename # test

        fout = open(filename, "wb")

        fout.write(my_picture)

        fout.close()
        webbrowser.open(filename)

        random=raw_input("please handin random:")
      

        rpassword = self.get_rpassword(self.password)
        login_params = {
            'username': self.username,
            'password': rpassword,
            'randomCode':random
         
        }
       
        req = urllib2.Request(LOGIN_URL, urllib.urlencode(login_params), {
            "Referer": MAIN_INDEX_URL})

        res=urllib2.urlopen(req)
        result = res.read()


        strStr1=""
        for cookie in self.cj:
             strStr1+=cookie.name
             strStr1+="="
             strStr1+=cookie.value
             strStr1+=";"
        print  strStr1

        ghost = Ghost()
        #open webkit
          
        headers = {    
         "Cookie": strStr1
        }
        ghost.open(GETDATA_URL,'get',headers)
      
        result, resources = ghost.evaluate("document.getElementById('password').value;")     
       
        print result

        ghost.open(GETDATA_CLICK_URL,'get',headers)
        result, resources = ghost.evaluate("document.getElementById('textspan').innerHTML;")
        print result

        result, resources = ghost.evaluate("document.getElementById('button1').click('xcvxc');")

        result, resources = ghost.evaluate("document.getElementById('textspan').innerHTML;")
        print result


       
          
    def get_rpassword(self,password):
       
        return password

if __name__ == '__main__':
 
    ua = UserAction(username = 'admin',password = 'admin')
 

    ua.login()
  





0 0