6.selenium - 封装常用工具类-验证码获取、生成随机字符串

前言

把常用的工具类封装好,用到的时候直接调用即可。
前面已经实现自动识别验证码,把识别验证码这部分内容进行封装,
还有经常使用的随机生成字符串。


import os
import random
import string

from selenium import webdriver
import time
from PIL import Image
import ddddocr
ocr = ddddocr.DdddOcr()


# 抠图、识别
def get_code(browser, id):
    """
    :param browser: 驱动
    :param id:      验证码图片的 id
    :return:        返回 res 验证码图片
    """
    # 把图片放在 screenshots 目录下
    path = os.path.dirname(os.path.dirname(__file__)) + '\\screenshots'
    picture_name1 = path + '\\' + 'login.png'
    # 保存第一张截图
    browser.save_screenshot(picture_name1)
    # 定位元素  captchaImg
    ce = browser.find_element_by_id(id)
    # 打印元素位置、元素尺寸
    print(ce.location, ce.size)
    # 要抠验证码的图,先获取元素参数

    # 坐标有时候要自己调节,参考这篇文章第八点,多试试二三十次,就可以截出来了。
    # https://www.cnblogs.com/mypath/articles/6646858.html

    left = ce.location.get('x') + 210
    top = ce.location.get('y') + 100
    r_size = ce.size.get('width') + 15
    h_size = ce.size.get('height') + 10
    right = r_size + left
    height = h_size + top
    # 读取刚才截的第一张图
    im = Image.open(picture_name1)
    # 抠图
    img = im.crop((left, top, right, height))
    # 验证码块的图片
    picture_name2 = path + '\\' + 'code.png'
    # 保存图片
    img.save(picture_name2)
    time.sleep(2)

    # 识别
    try:
        with open(picture_name2, 'rb') as f:
            img_bytes = f.read()
        res = ocr.classification(img_bytes)
        return res
    except:
        print("获取验证码失败,请继续!")


# 随机生成 6 位字符串
def get_random_str():
    random_str = ''.join(random.sample(string.ascii_letters + string.digits, 6))
    return random_str


if __name__ == '__main__':
    browser = webdriver.Chrome()
    # 打开网站首页
    # browser.get("https://v3pro.houjiemeishi.com/PC/pages/login/login.html")
    browser.get("http://120.25.209.187:12306/jpress/admin/login")
    # 网页最大化
    browser.maximize_window()
    # 验证码图片的 id
    id = 'captchaImg'
    code = get_code(browser, id)
    print(code)

posted @ 2022-03-28 23:00  西瓜_皮  阅读(288)  评论(0编辑  收藏  举报