使用python制作验证码
方法一
简单型:使用random模块制作一个随机字母与数字的验证码
import random def make_code(n): res='' for i in range(n): num=str(random.randint(1,9))#随机选取1到9的一个整数 letter=chr(random.randint(65,90))#随机选大写英文的一个字母 group=random.choice([num,letter])#随机选取整数还是大写字母 res+=group#循环次数加到空字符串中 return res print(make_code(4))
方法二
进阶型:使用random和pillow模块制作图形验证码
pillow不是自带库,需要自行安装,pip install pillow
import random import from PIL import Image, ImageDraw, ImageFont, ImageFilter from io import BytesIO def get_valid_code(): # 随机字母数字: def rndChar(): char_num = random.randint(0, 9) char_upper=chr(random.randint(65, 90)) char_lower=chr(random.randint(97, 122)) char_str=str(random.choice([char_num,char_lower,char_upper])) return char_str # 随机颜色1: def rndColor(): return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255)) # 随机颜色2: def rndColor2(): return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) # 240 x 60: width = 60 * 5 height = 60 image = Image.new('RGB', (width, height), (0,0,0)) # 创建Font对象: font = ImageFont.truetype(r'static\font\calligraph421-bt-roman.woff.ttf', 40) # 创建Draw对象: draw = ImageDraw.Draw(image) # 填充每个像素(画点): for x in range(width): for y in range(height): draw.point((x, y), fill=rndColor()) # 输出文字: random_code='' for t in range(5): char_str=rndChar() draw.text((60 * t + 10, 5), char_str, font=font, fill=rndColor2()) random_code+=char_str # 模糊处理: image = image.filter(ImageFilter.SMOOTH) # 其他一些画图功能 # 画线 # draw.line() # 保存到内存中 f=BytesIO() image.save(f,'jpeg') data=f.getvalue() return data res=get_valid_code() print(res)