温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
  • 首页 > 
  • 教程 > 
  • 开发技术 > 
  • 使用python3怎么提高识别图片验证码实现一个自动登录功能

使用python3怎么提高识别图片验证码实现一个自动登录功能

发布时间:2021-01-29 17:18:18 来源:亿速云 阅读:266 作者:Leah 栏目:开发技术

本篇文章为大家展示了使用python3怎么提高识别图片验证码实现一个自动登录功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

会用到的库的

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怎么提高识别图片验证码实现一个自动登录功能

上述内容就是使用python3怎么提高识别图片验证码实现一个自动登录功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI