会用到的库的

1、selenium的webdriver
2、tesserocr或者pytesseract进行图像识别
3、pillow的image进行图片处理

from selenium import webdriver
import tesserocr
from pil import image

获取验证码图片方法1:

def get_code_image(file_name):
 driver.save_screenshot(file_name) # 截取整个屏幕并保存
 code_element = driver.find_element_by_class_name("verify_code_img___1mei_") # 定位到验证码元素
 left = code_element.location['x'] # 定位到截图位置
 top = code_element.location['y']
 right = code_element.size['width'] + left
 bottom = code_element.size['height'] + top
 im = image.open(file_name) # 从文件读取截图,截取验证码位置再次保存
 img = im.crop((left, top, right, bottom))
 img.save(file_name)
 return file_name

获取验证码图片方法2:

def get_code_image(file_name):
 code_element = driver.find_element_by_class_name("verify_code_img___1mei_") # 定位到验证码元素 
 code_element.screenshot(file_name)

注:此方法截图时屏幕会闪动,可能引发bug,如下图,目前没有解决

处理验证码图片

def deal_code_image(file_name):
 image = image.open(file_name)
 # image.show() #查看处理前的图片
	# 处理图片去除干扰
 # 将图片转化为灰度图像
 image = image.convert('l')
 
 threshold = 90 # 设置临界值,临界值可调试
 table = []
 for i in range(256):
  if i < threshold:
   table.append(0)
  else:
   table.append(1)

 image = image.point(table, '1')
 # image.show() #查看处理后的图片
 # 1:使用tesseract库识别图片中的验证码
 # res = tesserocr.image_to_text(image)
 # 2:使用pytesseract库识别图片中的验证码
 res = pytesseract.image_to_string(image)

 # print(res) #查看识别出来的文案
 res = res.replace(" ", "") #去除结果中的空格
 return res

处理前的图片,有干扰,无法识别

处理后的图片,基本可以识别

识别结果不一定准确,如果验证码输入错误,可以点击换一张图片再次识别,多次尝试,本次不做说明

到此这篇关于python3定位并识别图片验证码实现自动登录的文章就介绍到这了,更多相关python识别图片验证码实现自动登录内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!