最近在导入某站数据(正经需求),看到他们的登录需要验证码,
本来并不想折腾的,然而Cookie有效期只有一天。
已经收到了几次夜间报警推送之后,实在忍不住。
得嘞,还是得研究下模拟登录。
于是,秃头了两个小时gang出来了。
预警
- 二值化、普通降噪、8邻域降噪
- tesseract、tesserocr、PIL
如果都了解这些东西,这文章就不用看了,直接跳到参考文献咯。
代码地址: https:// github.com/liguobao/pyt hon-verify-code-ocr
开始搞事
批量下载验证码图片
import shutil import requests from loguru import logger for i in range(100): url = 'http://xxxx/create/validate/image' response = requests.get(url, stream=True) with open(f'./imgs/{i}.png', 'wb') as out_file: response.raw.decode_content = True shutil.copyfileobj(response.raw, out_file) logger.info(f"download {i}.png successfully.") del response
第一步,直接上识别代码看看效果。
from PIL import Image import tesserocr img = Image.open("./imgs/98.png") img.show() img_l = img.convert("L")# 灰阶图 img_l.show() verify_code1 = tesserocr.image_to_text(img) verify_code2 = tesserocr.image