使用Python生成验证码
在本文中,我们将看到如何使用Python包 captcha 生成验证码,以图片形式生成我们自己的验证码(Completely Automated Public Turing Test to Tell Computers and Humans Apart)。 CAPTCHA 是一种挑战-响应认证安全机制。 CAPTCHA 可防止自动化系统读取图片中扭曲的字符。
安装:
pip install captcha
生成图像验证码:
在这里,我们将生成一个图像验证码:
分步实施:
步骤 1:导入模块并创建ImageCaptcha()的实例。
image = ImageCaptcha(width = 280, height = 90)
第 2 步:使用image.generate(CAPTCHA_Text)创建图像对象。
data = image.generate(captcha_text)
第 3 步:将图像保存到文件image.write() 中。
image.write(captcha_text, 'CAPTCHA.png')
下面是完整的实现:
Python3
# Import the following modules
from captcha.image import ImageCaptcha
# Create an image instance of the gicen size
image = ImageCaptcha(width = 280, height = 90)
# Image captcha text
captcha_text = 'GeeksforGeeks'
# generate the image of the given text
data = image.generate(captcha_text)
# write the image on the given file and save it
image.write(captcha_text, 'CAPTCHA.png')
Python3
# Import the following modules
from captcha.audio import AudioCaptcha
# Create an audio instance
audio = AudioCaptcha()
# Audio captcha text
captcha_text = "5454"
# generate the audio of the given text
audio_data = audio.generate(captcha_text)
# Give the name of the audio file
audio_file = "audio"+captcha_text+'.wav'
# Finally write the audio file and save it
audio.write(captcha_text, audio_file)
输出:
生成音频验证码:
在这里,我们将生成一个音频验证码:
分步实施:
步骤 1:导入模块并创建一个AudioCaptcha()实例。
image = audioCaptcha(width = 280, height = 90)
第 2 步:使用audio.generate(CAPTCHA_Text)创建一个音频对象。
data = audio.generate(captcha_text)
第 3 步:将图像保存到文件audio.write()。
audio.write(captcha_text, audio_file)
下面是完整的实现:
蟒蛇3
# Import the following modules
from captcha.audio import AudioCaptcha
# Create an audio instance
audio = AudioCaptcha()
# Audio captcha text
captcha_text = "5454"
# generate the audio of the given text
audio_data = audio.generate(captcha_text)
# Give the name of the audio file
audio_file = "audio"+captcha_text+'.wav'
# Finally write the audio file and save it
audio.write(captcha_text, audio_file)
输出: