python 处理图片验证码

    xiaoxiao2021-12-14  18

    在做自动化测试的时候一般登录都有验证码,若验证码为图片验证码,则可以用python的Pillow对验证码图片进行操作

    注:PIL 只支持到Python 2.7。PIL官方网站:http://www.pythonware.com/products/pil/,Pillow是PIL的一个派生分支

    1. 安装Pillow

    在命令行使用PIP安装:

    pip install Pillow

    或在命令行使用easy_install安装:

    easy_install Pillow

    安装完成后,使用from PIL import Image就引用使用库了。比如:

    from PIL import Image

    im = Image.open("a.jpg")

    im.show()

    因为我是windows7 64位的,按以上办法安装失败(PIL官网提供的下载包都是32位的

    然后,有人提供了非官方的64位库:http://www.lfd.uci.edu/~gohlke/pythonlibs/

    叫做Pillow,下载下来,是个 .whl 结尾的文件,这个其实就是python使用的一种压缩文件(后缀名改成zip,可以打开查看文件)

    这个需要用 pip 安装:

    pip install Pillow-2.7.0-cp27-none-win_amd64.whl  即可。

    注:若是安装的Pillow ,在使用时需要 ‘ from PIL import Image' 代替 'import Image'

    ------------------------------------------------------------------------------------------------------------------------------------------

    在安装 Pillow的时候,发现安装不上提示 pip的版本过低了需要升级:

    输入指令

    python -m pip install -U pip(要注意大小写,以免安装失败)

    会自动卸载以前的旧版本,并下载安装新版本。

    结果更新pip提示有问题,再次 输入 python -m pip install -U pip ,提示 文件已到达指定目录,根据提示的文件路径手动删除已下载pip文件(高版本pip文件)

    再在 命令行 输入 python -m pip install -U pip 即可

    相关文档:http://www.th7.cn/Program/Python/201602/768304.shtml

    ---------------------------------------------------------------------------------------------------------------

    2.安装 pytesser 

    pytesser下载地址:http://download.csdn.net/download/pyliang_2008/5564135

    相关文档:http://blog.csdn.net/bone_ace/article/details/50436587

    pytesser下载后解压到pytesser文件中,在把文件移动到python安装目录(如:C:/Python27/Lib/site-packages),然后在该目录下添加 pytesser.pth 文件内容已为pytesser

    然后把pytesser文件中pytesser.py 的文件名改为__init__.py,在打开该文件把 import Image 改为 from PIL import Image,再把 tesseract_exe_name 的值改为

    'C:/Python27/Lib/site-packages/pytesser/tesseract.exe'(对应python安装目录)

    然后 添加环境,在我的电脑-属性-高级系统设置-环境变量-path 中添加 C:/Python27/Lib/site-packages;C:/Python27/Lib/site-packages/pytesser

    3读取图片验证码

    案例1:

    from pytesser import *

    from PIL import Image

    def xx():

       # 打开图片

        image = Image.open('E:/TestPython/function/imgs/site.png')

        # 识别图片验证码

        print(image_to_string(image))

    def xx1():

        image = Image.open('E:/TestPython/function/imgs/site.png')

        # 设定二值图像转换''L''表示灰度,''1''表示二值图模式

        out = image .convert('1')

        # 保存图像

        out.save('a.jpg')

        # 对图片进行截取crop(x1, y1, x2, y2)

        # x1:距离图片左边x1px,x2:距离图片左边x2px;

        # y1:距离图片顶部y1px,y2:距离图片顶部y2px;

        # crop 会截取图片(x2-x1)的宽度,(y2-y1)的高度,故x2>x1,y2>y1

        # 设置截取坐标

        box = (10, 2, 23, 40)

        croplmg = out.crop(box)

        croplmg.save('1.jpg')

        tx = []

        image1 = Image.open('1.jpg')

       # 识别图片验证码

        tx.append(image_to_string(image1))

    if __name__ == '__main__':

        xx1()

    转载请注明原文地址: https://ju.6miu.com/read-964405.html

    最新回复(0)