网络编程
位置:首页>> 网络编程>> Python编程>> python3定位并识别图片验证码实现自动登录功能

python3定位并识别图片验证码实现自动登录功能

作者:茶几mzcy  发布时间:2022-07-23 13:23:59 

标签:python,图片验证码,自动登录

会用到的库的

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


from selenium import webdriver
import tesserocr
from PIL import Image

tesserocr的安装.

获取验证码图片方法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,如下图,目前没有解决

python3定位并识别图片验证码实现自动登录功能

处理验证码图片


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定位并识别图片验证码实现自动登录功能

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

python3定位并识别图片验证码实现自动登录功能

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

来源:https://blog.csdn.net/zloveyll/article/details/113246855

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com