python_字母/数字验证码获取

前言

  • 在使用自动化登录网站时,经常输入用户名和密码后就会遇到验证码,今天介绍一款通用验证码识别 OCR库,它的名字是ddddocr。

一、安装

pip install ddddocr

二、使用ddddocr

获取数字/字母验证码

在这里插入图片描述

  • 方法一
import os
import ddddocr
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import Byclass GetVerificationCode:def __init__(self):# 创建了一个Chrome浏览器的WebDriver实例self.drive = webdriver.Chrome()# 最大化窗口self.drive.maximize_window()# 隐式等待,设置最大的等待时长,只对查找元素(find_elementXXX)生效self.drive.implicitly_wait(2)def getverification(self, location):'''获取验证码信息'''# 获取当前文件的位置current_location = os.path.dirname(__file__)# 截取当前网页并放到指定目录下,并命名为printscreen,该截图中有我们需要的验证码self.drive.save_screenshot(f'{current_location}\\printscreen.png')# 定位验证码位置position = self.drive.find_element(By.CSS_SELECTOR, location)# 获取验证码x, y轴坐标location = position.location# 获取验证码的宽度、高度size = position.size# 需要截取的位置坐标rangle = (int(location['x']), int(location['y']),int(location['x'] + size['width']),int(location['y'] + size['height']))# 打开截图i = Image.open(f'{current_location}\\printscreen.png')# 使用Image的crop函数,从截图中再次截取我们需要的区域fimg = i.crop(rangle)fimg = fimg.convert('RGB')# 保存我们截下来的验证码图片,并读取验证码内容fimg.save(f'{current_location}\\code.png')# 获取验证码ocr = ddddocr.DdddOcr()with open(f'{current_location}\\code.png', 'rb') as f:img_bytes = f.read()self.res = ocr.classification(img_bytes)print('识别出的验证码为:' + self.res)def login(self):'''登录'''# 打开网站self.drive.get('需要获取验证码的网站')# 获取验证码self.getverification('.bgw')if __name__ == '__main__':run = GetVerificationCode()run.login()
  • 方法二
import os
import ddddocr
from selenium import webdriver
from selenium.webdriver.common.by import Byclass GetVerificationCode:def __init__(self):# 创建了一个Chrome浏览器的WebDriver实例self.drive = webdriver.Chrome()# 最大化窗口self.drive.maximize_window()# 隐式等待,设置最大的等待时长,只对查找元素(find_elementXXX)生效self.drive.implicitly_wait(2)def getVerification(self, location):'''获取验证码信息'''# 获取当前文件的位置current_location = os.path.dirname(__file__)# 定位验证码位置position = self.drive.find_element(By.CSS_SELECTOR, location)# 截取页面上固定元素的图片(验证码)position.screenshot(f'{current_location}\\code.png')# 获取验证码ocr = ddddocr.DdddOcr()with open(f'{current_location}\\code.png', 'rb') as f:img_bytes = f.read()self.res = ocr.classification(img_bytes)print('识别出的验证码为:' + self.res)def login(self):'''登录'''# 打开网站self.drive.get('需要获取验证码的网站')# 获取验证码self.getVerification('.bgw')if __name__ == '__main__':run = GetVerificationCode()run.login()


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部