四行代码生成图片验证码

日常的网站或app中,可以使用到图片验证码。

安装:

pip install captcha

使用:

from captcha.image import ImageCaptcha
image = ImageCaptcha()
data = image.generate('1234')
image.write('1234', 'out.png')

程序运行后,在当前目录下,看到已经生成验证码了。

还可以利用它生成大量的图片验证码,作为机器学习模型的训练和模型的测试数据。这样就可以实现一个验证码识别服务。用于网络爬虫。

参考原文—— https://mp.weixin.qq.com/s/OhohjCrRn21dZNCBHKESzw

另:原文代码有误。本博文已修正。

以上。

------------------------神秘的分割线----------------------------

拓展使用:

from random import randint
from captcha.image import ImageCaptcha


list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
	'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
	'w', 'x', 'y', 'z',
	'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
		'W', 'X', 'Y', 'Z']
chars = ''
for i in range(4):
    chars += list[randint(0, 63)]
print(chars)

image = ImageCaptcha()
data = image.generate_image(chars)
data.show()  # 显示生成的验证码图片
image.write(chars, 'out.png')  # 生成png格式验证码图片

运行这段代码,本地目录保存了out.png:

以上。

原文地址:https://www.cnblogs.com/lovebkj/p/12745461.html