Python 文字验证码
![classDiagram](
简介
验证码(Captcha,全称:Completely Automated Public Turing test to tell Computers and Humans Apart)是一种用于识别用户是人还是计算机的技术。文字验证码是其中一种常见的形式,通过生成一段随机的文字,要求用户进行正确的输入以验证身份。
在开发Web应用程序、爬虫、自动化测试等场景中,验证码一直是一个挑战。本文将介绍如何使用Python生成和验证文字验证码,并提供代码示例。
生成文字验证码
首先,我们需要生成一段随机的文字验证码。Python的random
模块提供了生成随机数的方法,我们可以利用它生成随机的文字验证码。
以下是一个生成文字验证码的代码示例:
import random
import string
def generate_captcha(length=4):
"""
生成文字验证码
Parameters:
- length: 验证码长度,默认为4
Returns:
- captcha: 生成的验证码字符串
"""
captcha = ''.join(random.choices(string.ascii_letters + string.digits, k=length))
return captcha
以上代码中,我们利用random.choices
方法从字母和数字的集合中随机选择字符,并通过join
方法将生成的字符拼接成字符串作为验证码。
生成文字验证码图片
为了更好地展示文字验证码,我们可以将生成的文字验证码添加到图片中。Python的Pillow
库提供了处理图像的功能,我们可以利用它生成文字验证码图片。
以下是一个生成文字验证码图片的代码示例:
from PIL import Image, ImageDraw, ImageFont
def generate_captcha_image(captcha, font_path='arial.ttf', font_size=30, image_size=(120, 40), text_color=(0, 0, 0), bg_color=(255, 255, 255)):
"""
生成文字验证码图片
Parameters:
- captcha: 验证码字符串
- font_path: 字体文件路径,默认为arial.ttf
- font_size: 字体大小,默认为30
- image_size: 图片尺寸,默认为(120, 40)
- text_color: 文字颜色,默认为黑色
- bg_color: 背景颜色,默认为白色
Returns:
- image: 生成的验证码图片对象
"""
image = Image.new('RGB', image_size, bg_color)
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font_path, font_size)
text_width, text_height = draw.textsize(captcha, font=font)
text_position = ((image_size[0] - text_width) // 2, (image_size[1] - text_height) // 2)
draw.text(text_position, captcha, font=font, fill=text_color)
return image
以上代码中,我们利用Pillow
库创建一个新的图片对象,然后使用ImageDraw
和ImageFont
分别绘制文字和设置字体。最后,我们将生成的验证码字符串绘制在图片中心,并返回生成的图片对象。
验证文字验证码
生成文字验证码后,我们需要验证用户输入是否正确。验证文字验证码的过程是将用户输入的验证码与生成的验证码进行对比,判断是否一致。
以下是一个验证文字验证码的代码示例:
def verify_captcha(input_captcha, generated_captcha):
"""
验证文字验证码
Parameters:
- input_captcha: 用户输入的验证码
- generated_captcha: 生成的验证码
Returns:
- is_valid: 验证结果,True表示一