Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 623|回复: 0

selenium UI自动化解决验证码的五种方法

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-5-16 11:43:45 | 显示全部楼层 |阅读模式

     

     

     

     

    TesseractPy3.py

    #coding=utf-8
     
    import os
    import subprocess
    import traceback
    import logging
     
    from PIL import Image # 来源于Pillow库
     
    TESSERACT = 'tesseract' # 调用的本地命令名称
    TEMP_IMAGE_NAME = "temp.bmp" # 转换后的临时文件
    TEMP_RESULT_NAME = "temp" # 保存识别文字临时文件
    CLEANUP_TEMP_FLAG = True # 清理临时文件的标识
    INCOMPATIBLE = True # 兼容性标识
     
    def image_to_scratch(image, TEMP_IMAGE_NAME):
      # 将图片处理为兼容格式
      image.save(TEMP_IMAGE_NAME, dpi=(200,200))
     
    def retrieve_text(TEMP_RESULT_NAME):
      # 读取识别内容
      inf = open(TEMP_RESULT_NAME + '.txt','r')
      text = inf.read()
      inf.close()
      return text
     
    def perform_cleanup(TEMP_IMAGE_NAME, TEMP_RESULT_NAME):
      # 清理临时文件
      for name in (TEMP_IMAGE_NAME, TEMP_RESULT_NAME + '.txt', "tesseract.log"):
        try:
          os.remove(name)
        except OSError:
          pass
     
    def call_tesseract(image, result, lang):
      # 调用tesseract.exe,将识读结果写入output_filename中
      args = [TESSERACT, image, result, '-l', lang]
      proc = subprocess.Popen(args)
      retcode = proc.communicate()
     
    def image_to_string(image, lang, cleanup = CLEANUP_TEMP_FLAG, incompatible = INCOMPATIBLE):
      # 假如图片是不兼容的格式并且incompatible = True,先转换图片为兼容格式(本程序将图片转换为.bmp格式),然后获取识读结果;如果cleanup=True,操作之后删除临时文件。
      logging.basicConfig(filename='tesseract.log')
      try:
        try:
          call_tesseract(image, TEMP_RESULT_NAME, lang)
          text = retrieve_text(TEMP_RESULT_NAME)
        except Exception:
          if incompatible:
            image = Image.open(image)
            image_to_scratch(image, TEMP_IMAGE_NAME)
            call_tesseract(TEMP_IMAGE_NAME, TEMP_RESULT_NAME, lang)
            text = retrieve_text(TEMP_RESULT_NAME)
          else:
            raise
        return text
      except: 
        s=traceback.format_exc()
        logging.error(s)
      finally:
        if cleanup:
          perform_cleanup(TEMP_IMAGE_NAME, TEMP_RESULT_NAME)
    

     

    #coding=utf-8
     
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support.ui import Select
    from selenium.common.exceptions import NoSuchElementException
    from selenium.common.exceptions import NoAlertPresentException
    from PIL import Image
    import unittest, time, re
    from TesseractPy3 import *
     
    class lgoin(unittest.TestCase):
      def setUp(self):
        self.driver = webdriver.Ie()
        self.driver.implicitly_wait(30)
        self.base_url = 'http://127.0.0.1:8080/test' # 要测试的链接
        self.title = '某管理平台' # 测试网站的Title
        self.verificationErrors = []
        self.accept_next_alert = True
     
      def test_lgoin(self):
        driver = self.driver
        driver.get(self.base_url)
        driver.maximize_window()
        driver.save_screenshot('All.png') # 截取当前网页,该网页有我们需要的验证码
        imgelement = driver.find_element_by_class_name('kaptchaImage')
        location = imgelement.location # 获取验证码x,y轴坐标
        size = imgelement.size # 获取验证码的长宽
        rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height'])) # 写成我们需要截取的位置坐标
        i = Image.open("All.png") # 打开截图
        result = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域
        result.save('result.jpg')
        text = image_to_string('result.jpg', 'eng').strip()
     
        assert self.title in driver.title
     
        driver.find_element_by_id(u'userCode').clear()
        driver.find_element_by_id(u'userCode').send_keys('XXXXXX') # 用户名
        driver.find_element_by_id(u'password').clear()
        driver.find_element_by_id(u'password').send_keys('XXXXXX') # 密码
        #driver.find_element_by_name('verifyCode').clear()
        driver.find_element_by_name('verifyCode').send_keys(text)
        driver.find_element_by_name('submit').submit()
     
     
      def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e: return False
        return True
     
      def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException as e: return False
        return True
     
      def close_alert_and_get_its_text(self):
        try:
          alert = self.driver.switch_to_alert()
          alert_text = alert.text
          if self.accept_next_alert:
             alert.accept()
          else:
            alert.dismiss()
          return alert_text
        finally: self.accept_next_alert = True
     
      def tearDown(self):
        #self.driver.quit()
        self.assertEqual([], self.verificationErrors)
     
    if __name__ == "__main__":
      unittest.main()
    

     

     

    # coding=utf-8
     
    from selenium import webdriver
    import time 
     
    driver = webdriver.Firefox()
    driver.get("http://www.xxxxxx.com/") # 要登陆的网站
     
    driver.add_cookie(cook) # 这里添加cookie,有时cookie可能会有多条,需要添加多次
    time.sleep(3) 
     
    # 刷新下页面就可以看到登陆成功了
    driver.refresh() 

    BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream("/Users/pangyongjuan/IdeaProjects/Zmbx/src/test/java/code.txt")));
    ​
            String code = null;
    ​
            while((code = reader.readLine()) != null){
                System.out.println("验证码是:---->"+ code);
                driver.findElement(By.id("pin")).sendKeys(code);
            }
    

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-23 03:30 , Processed in 0.056851 second(s), 27 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表