脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python selenium UI自动化解决验证码的4种方法

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

2021-01-01 00:08地空神一 Python

本篇文章主要介绍了python selenium UI自动化解决验证码的4种方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

本文介绍了python selenium UI自动化解决验证码的4种方法,分享给大家,具体如下:

测试环境

  1. windows7+
  2. firefox50+
  3. geckodriver # firefox浏览器驱动
  4. python3
  5. selenium3

selenium UI自动化解决验证码的4种方法:去掉验证码、设置万能码、验证码识别技术-tesseract、添加cookie登录,本次主要讲解验证码识别技术-tesseract和添加cookie登录。

1. 去掉验证码

去掉验证码,直接通过用户名和密码登陆网站。

2. 设置万能码

设置万能码,就是不管什么情况,输入万能码,都可以成功登录网站。

3. 验证码识别技术-tesseract

准备条件

  1. tesseract,下载地址:https://github.com/parrot-office/tesseract/releases/tag/3.5.1
  2. Python3.x,下载地址:https://www.python.org/downloads/
  3. pillow(Python3图像处理库)

安装好Python,通过pip install pillow安装pillow库。然后将tesseract中的tesseract.exe和testdata文件夹放到测试脚本所在目录下,testdata中默认有eng.traineddata和osd.traineddata,如果要识别汉语,请自行下载对应包。

以下是两个主要文件,TesseractPy3.py是通过python代码去调用tesseract以达到识别验证码的效果。code.py是通过selenium获取验证码图片,进而使用TesseractPy3中的函数得到验证码,实现网站的自动化登陆。

TesseractPy3.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#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)

code.py

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#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()

最后,执行命令python code.py,就可以成功自动登录网站。

注意:

由于受验证码图片质量以及清晰度的影响,并不是每一次都能成功登陆。

4. 添加cookie登录

首先获取网站登陆后的cookie,然后通过添加cookie的方式,实现网站登陆的目的。我们用cook来表示xxxxxx的登录后的cookie。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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()

注意:

登录时有勾选下次自动登录的请勾选,浏览器提示是否保存用户密码时请选择确定,这样获取的cookie成功登陆的机率比较高

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/97868d722e14

延伸 · 阅读

精彩推荐