1说明: 1。1captcha: CompletelyAutomatedPublicTuringTesttoTellComputersandHumansApart。 全自动区分计算机与人类的图灵测试。(名字很牛,所以功能很强大!!) 1。2captcha是一个生成验证码的python库,它支持图片验证码和语音验证码,我今天重点仔细讲解它的图片验证码。 1。3一秒入门,简单且通俗易懂。 1。4补充一点:回应一个网友的回答,我的第一张图片来自今日头条的免费正版图库,操作如下。 小插入:夹带一点私活 2准备: 2。1官网:https:pypi。orgprojectcaptchahttps:github。comlepturecaptcha 2。2环境: 华为笔记本电脑、深度deepinlinux操作系统、谷歌浏览器、python3。8和微软vscode编辑器。 2。3安装:pipinstallcaptcha本机安装,国内源,推荐sudopip3。8installihttps:mirrors。aliyun。compypisimplecaptcha 重要知识点,本代码均为注释版 3默认图片展示: 3。1代码:fromcaptcha。imageimportImageCaptchaimportnumpyasnpimportrandomimportstring随机生成数字(09)、小写字母的字符串(az)、大写字母的字符串(AZ)charactersstring。digitsstring。asciilowercasestring。asciiuppercaseprint(characters)窗口的大小、字体(hwfs,自己下载,放在根目录下)设置参数,默认设置ImageCaptcha(width160,height60,fontsNone,fontsizesNone)所有字体大小指定为100,注意有〔〕中括号注意:高120字体100,否则不舒服generatorImageCaptcha(width300,height120,fonts〔hwfs。ttf〕,fontsizes〔100〕)字体大小随机不同generatorImageCaptcha(width300,height120,fonts〔hwfs。ttf〕,fontsizesrange(20,60))随机获取取4个字符串randomstr。join(〔random。choice(characters)foriinrange(4)〕)字符串,字符颜色,背景颜色(255,255,255)白色;(10,200,153)草绿色,(205,20,25)红色,自己可以自定义参数:createcaptchaimage(chars,color,background)imggenerator。createcaptchaimage(randomstr,(10,200,153),(205,20,25))print(randomstr)保存img。save(homexgjDesktopcaptchagenerate。png)默认图片编辑器展示img。show(titlepiccode)标题名设置无效img。show()标题名设置无效 3。2图: 阿拉伯数字和大小写字母组合形式 4matplotlib法挂载和显示: 4。1代码:fromcaptcha。imageimportImageCaptchaimportmatplotlib。pyplotaspltimportrandom举例,加入指定汉字,大小写字母注意本机matplotlib已经设置中文,既往文章有提到,有3种方法,此处采纳其中最简单一种textz〔0,1,2,3,4,5,6,7,8,9,大,小,好,A,B,e〕这一步生成验证码的图片框架imageImageCaptcha(width90,height30,fonts〔hwfs。ttf〕,fontsizes〔30〕)captchatext〔〕随机生成6个foriinrange(6):crandom。choice(textz)captchatext。append(c)print(captchatext)captchatext。join(captchatext)print(captchatext)默认法,需要设置字体颜色和背景颜色captchaimageimage。createcaptchaimage(captchatext)报错captchaimageimage。createcaptchaimage(captchatext,(10,200,153),(25,20,255))报错图片挂在plt上plt。imshow(captchaimage)plt。title(captchatext)显示图标的标题,为显示字符串plt。show() 4。2图: 5联合PILmatplotlib法: 5。1代码:fromcaptcha。imageimportImageCaptchaimportmatplotlib。pyplotaspltfromPILimportImageimportrandom总字符串列表textz〔0,1,2,3,4,5,6,7,8,9,喜,美,好,A,C,g,e〕生成验证码框架,注意字体与高度关系imageImageCaptcha(width200,height50,fonts〔hwfs。ttf〕,fontsizes〔30〕)captchatext〔〕foriinrange(6):crandom。choice(textz)captchatext。append(c)print(captchatext)生成随机的验证码captchatext。join(captchatext)print(captchatext)采用PIL法,较佳背景颜色和字体颜色随机自动生成,还有干扰点和线captchaimage。generate(captchatext)captchaimageImage。open(captcha)保存图片image。write(captchatext,outputhomexgjDesktopcaptchaxx。png)plt。imshow(captchaimage)plt。title(captchatext)图标标题名显示生成的验证码plt。show() 5。2图展示: 自己整理并分享出来 喜欢的人,请点赞、关注、转发、评论和收藏。 如果复制全文,不是在今日头条,在别的平台,请您注明出处即可,谢谢。