通过服务器获取验证码
测试自动化在遇见有验证码的情况时通常的做法是:
1. 去掉验证码
2. 设置万能验证码
3. 验证码识别技术
4. 记录cookie
以上方法各有优缺点,这里不再赘述,只简单介绍一种不用任何改动简单有效不影响流程的方法,直接上源码:
# -*- coding:utf-8 -*-
# Python27 import paramiko,datetime import selenium.webdriver as webdriver # 连接服务器获取验证码 def getpin(sessionid): hostname = '111.111.111.111' port = 8989 username = 'testname' key_file = 'D:\Butterfly\sandbox' date = datetime.datetime.now().strftime('%Y-%m-%d') key = paramiko.RSAKey.from_private_key_file(key_file) sessionid = sessionid s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname,port,username,pkey=key,timeout=5) cmd = "tac /opt/tomcat/logs/catalina." + date + ".out | grep " + sessionid + ":validateCode | sed -n '1p'" print cmd stdin,stdout,stderr = s.exec_command(cmd) cmd_result = stdout.read(),stderr.read() print cmd_result for line in cmd_result: if line : pincode = line[-5:-1] s.close() return pincode # 打开浏览器获取session driver = webdriver.Chrome() driver.get('https://new.xxx.com/') cookies = driver.get_cookies() for cookie in cookies: print "%s -> %s" % (cookie['name'], cookie['value']) if cookie['name'] == 'JSESSIONID': sessionid = cookie['value'] if sessionid: print "sessionid is :" + sessionid pincode = getpin(sessionid) else: print "获取session失败" # 页面信息填写 driver.find_element_by_id("mobile").send_keys("18122223333") driver.find_element_by_id("password").send_keys("11111111") driver.find_element_by_id("validateCode").send_keys(pincode)
运行结果为:
_check_code_loginregister -> 1460449532856 JSESSIONID -> 11A50AF9CF61E4EA541B4AE6BE516D20-n1 Hm_lvt_04da9d36c446fb5cac2ee84477faa8e8 -> 1460449432 Hm_lpvt_04da9d36c446fb5cac2ee84477faa8e8 -> 1460449432 sessionid is :11A50AF9CF61E4EA541B4AE6BE516D20-n1 tac /opt/tomcat/logs/catalina.2016-04-12.out | grep 11A50AF9CF61E4EA541B4AE6BE516D20-n1:validateCode | sed -n '1p' ('2016-04-12 16:25:33,351 [http-bio-8080-exec-2] INFO com.gamaxpay.website.util.VerifyCodeServlet - 11A50AF9CF61E4EA541B4AE6BE516D20-n1:validateCode:https://new.mo9.com/verifyCodeServlet:5TBV\n', '')
代码比较简单,不再赘述。原理简单说就是:将sessionid和验证码记录在日志文件中,调起浏览器后根据sessionid去浏览器中取出验证码即可