韦奇_UI_ai自动化获取图片验证码

UI自动化获取图片验证码

代码

test_ai.py

from time import sleep

from selenium import webdriver
from selenium.webdriver.common.by import By

from L5.AICode.ocr_code import OCRCode


class TestAi:

    def setup_class(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(10)
        # 打开页面
        self.driver.get("https://vip.ceshiren.com/#/ui_study/code")

    def teardown_class(self):
        self.driver.quit()

    def test_ai(self):
        # 获取验证码图片链接
        img_url = self.driver.find_element(By.CSS_SELECTOR, ".code1:nth-child(1) img").get_attribute("src")
        # 获取验证码内容
        code = OCRCode.get_by_ocr(img_url)
        # 输入验证码
        self.driver.find_element(By.CSS_SELECTOR, ".code1:nth-child(1) input").send_keys(code)
        # 点击确定
        self.driver.find_element(By.CSS_SELECTOR, ".code1:nth-child(1) button").click()
        # 断言验证码是否正确
        sleep(1)
        text = self.driver.find_element(By.CSS_SELECTOR, ".el-message p").text
        print(text)
        assert text == "验证成功"


ocr_code.py

from time import sleep

import easyocr
import requests
import cv2


class OCRCode:

    @classmethod
    def get_by_ocr(cls, img_url):
        # 使用requests发请求拿到图片结果
        result = requests.get(img_url, verify=False)
        # 保存图片到本地
        with open("code.png", "wb") as f:
            f.write(result.content)
        sleep(1)
        # opencv处理图片
        cls.opencv_image()
        # 实例化easyocr
        ocr = easyocr.Reader(['ch_sim', 'en'])
        # 识别图片内容
        code = ocr.readtext("result.png")[0][1].replace(" ", "")
        print(code)
        return code

    @classmethod
    def opencv_image(cls):
        # 读取图片
        image = cv2.imread("code.png")
        # 边缘保留滤波去噪
        image1 = cv2.pyrMeanShiftFiltering(image, sp=8, sr=60)
        # 灰度图片,颜色处理
        image2 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
        # 颜色取反
        cv2.bitwise_not(image2, image2)
        # 保存图片
        cv2.imwrite("result.png", image2)