selenium实现输入数字字母验证码

思路

1. 登录url

2. 获取验证码坐标

3. 根据桌标截图验证码

4. 对验证码进行识别

5. 自动输入验证码

测试代码

import os
import time
from io import BytesIO
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
import sys

import ddddocr

import uuid


if __name__ == '__main__':
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("http://172.16.12.129/DVWA/login.php")
    #driver.get('https://icpc.ldu.edu.cn/login')
    #driver.get('http://admin.dlszyht.com/login.php')
    #driver.get("https://icpc.ldu.edu.cn/login")
    time.sleep(2)
    # 执行js,对页面进行缩放,100 占 125 的 80%
    # driver.execute_script('document.body.style.zoom="0.8"')
    # 要截图的元素
    #element = driver.find_element_by_css_selector('#captcha')
    #element = driver.find_element("id", "su")
    #element = driver.find_element("id", "captcha").
    #element = driver.find_element("title", "看不清,换一个")
    #element = driver.find_element(By.TAG_NAME, "form")
    element = driver.find_element(By.CSS_SELECTOR, 'img[title="点击图片重新获取验证码"]')
    #element = driver.find_element("id", "vcodesrc")

    # 坐标
    x, y = element.location.values()
    # 宽高
    h, w = element.size.values()
    # x = element.location['x']  # 获取验证最左边位置
    # y = element.location['y']  # 获取验证码上边位置
    # w = x + element.size['width']  # 获取验证码右边位置
    # h = y + element.size['height']  # 获取验证码下边位置
    # 把截图以二进制形式的数据返回
    image_data = driver.get_screenshot_as_png()
    # 以新图片打开返回的数据
    screenshot = Image.open(BytesIO(image_data))

    # 对截图进行裁剪
    result = screenshot.crop((x, y, x + w, y + h))
    # 显示图片
    #result.show()
    pic_captcha_name = "{}{}{}{}".format(os.path.dirname(os.path.realpath(__file__)), "/tmpfile/", uuid.uuid4(), ".png")
    result.save(pic_captcha_name)

    #"""
    ocr = ddddocr.DdddOcr()
    with open(pic_captcha_name, 'rb') as f:
        img_bytes = f.read()
        res = ocr.classification(img_bytes)
        print(res)
    os.remove(pic_captcha_name)
    #"""

你可能感兴趣的:(爬虫,安全)