使用captcha模块即可直接生成验证码
码云链接
语言:python
python版本:Python 3.8.3
编译器:vscode
需要的模块:captcha,PIL
- 安装capthca模块
pip install -i https://pypi.douban.com/simple captcha
- 查看更多验证码的文章请点击传送门
- _Captcha类上面没框出来的我也不知道是啥
- 大概看一下源码的内容
- 父类_Captcha
- ImageCaptcha
- 所以实例化ImageCaptcha的时候,可以指定图片的大小和字体以及字体大小
- 现在指定一个参数看看
from captcha.image import ImageCaptcha
font_path = r'C:\Windows\Fonts\simfang.ttf'
img = ImageCaptcha(width=200,
height=100,
fonts=[font_path],
font_sizes=(42, 50, 56))
im = img.create_captcha_image(chars='哈哈哈哈', color='red', background='white')
im.show()
print(im.size)
print(type(im))
from captcha.image import ImageCaptcha
font_path = r'C:\Windows\Fonts\simfang.ttf'
for one in range(10, 42):
img = ImageCaptcha(width=200,
height=100,
fonts=[font_path],
font_sizes=(one, 50, 56))
im = img.create_captcha_image(chars='哈哈哈哈',
color='red',
background='white')
path = r'images/font_sizes_改变元祖索引0的大小/' + str(one) + '.png'
im.save(path)
print('验证码生成完成')
- 可以发现有的哈小,但是还是没有发现啥规律
- 改变索引1看看
from captcha.image import ImageCaptcha
font_path = r'C:\Windows\Fonts\simfang.ttf'
for one in range(10, 50):
img = ImageCaptcha(width=200,
height=100,
fonts=[font_path],
font_sizes=(42, one, 56))
im = img.create_captcha_image(chars='哈哈哈哈',
color='red',
background='white')
path = r'images/font_sizes_改变元祖索引1的大小/' + str(one) + '.png'
im.save(path)
print('验证码生成完成')
- 也是有的ha变小了,还是找不到啥规律
- 改变索引2看看
from captcha.image import ImageCaptcha
font_path = r'C:\Windows\Fonts\simfang.ttf'
for one in range(10, 50):
img = ImageCaptcha(width=200,
height=100,
fonts=[font_path],
font_sizes=(42, 50, one))
im = img.create_captcha_image(chars='哈哈哈哈',
color='red',
background='white')
path = r'images/font_sizes_改变元祖索引2的大小/' + str(one) + '.png'
im.save(path)
print('验证码生成完成')
- 我套阿
- 看下源码里这个font_sizes是要干啥
- 发现是PIL.ImageFont里面的方法
- 点进去查看一下该方法
- 继续点进去查看源码
- 试着打印一下这个方法的值
from captcha.image import ImageCaptcha
img = ImageCaptcha(
width=200,
height=100,
font_sizes=(42, 50, 52))
print(img.truefonts)
- 输出一个元组,长度为3
- 重新看了一下列表推导式
- 试着在ipython写了一下
- 那么仔细想一下就知道_truefonts的值就是一个元组,每个元组都是字体和大小就是咱们实例化的时候传进去的字体和大小,而且字体大小还是随机取的
- 嘿,知道是怎么一回事的话,那么font_sizes就好办了
- font_sizes解决
from captcha.image import ImageCaptcha
font_path = r'C:\Windows\Fonts\simfang.ttf'
img = ImageCaptcha(fonts=[font_path], font_sizes=(10, ))
im = img.create_captcha_image(chars='哈哈哈哈', color='red', background='white')
im.show()
- 这样字体的大小就是10咯
- 指定更大一些的字体大小
- font_sizes参数总结,如果长度为1,那么字体的大小就是这个数,如果长度不为>1,那么字体的大小就是随机选择元组里面的值,如果咱们前面才会出现有大有小的"哈"…顺便一提,这个四个的哈,每个字的大小都是随机的哦,看下图就知道了
- 关于ImageCaptcha类的__init__和truefonts就讲解到这吧,剩下的方法另起文章讲解,不然篇幅太长