微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python下调用pytesseract识别某网站验证码的实现方法

一、PyTesseract介绍

1、PyTesseract说明

PyTesseract最新版本0.1.6,网址:https://pypi.python.org/pypi/PyTesseract

Python-tesseract is a wrapper for google's Tesseract-OCR
( http://code.google.com/p/tesseract-ocr/ ). It is also useful as a
stand-alone invocation script to tesseract,as it can read all image types
supported by the Python Imaging Library,including jpeg,png,gif,bmp,tiff,
and others,whereas tesseract-ocr by default only supports tiff and bmp.
Additionally,if used as a script,Python-tesseract will print the recognized
text in stead of writing it to a file. Support for confidence estimates and
bounding Box data is planned for future releases.

翻译一下大意:

a、Python-tesseract是一个基于google's Tesseract-OCR的独立封装包;

b、Python-tesseract功能是识别图片文件中文字,并作为返回参数返回识别结果;

c、Python-tesseract支持tiff、bmp格式图片,只有在安装PIL之后,才能支持jpeg、gif、png等其他图片格式;

2、PyTesseract安装

INSTALLATION:

Prerequisites:
* Python-tesseract requires python 2.5 or later or python 3.
* You will need the Python Imaging Library (PIL). Under Debian/Ubuntu,this is
the package "python-imaging" or "python3-imaging" for python3.
* Install google tesseract-ocr from http://code.google.com/p/tesseract-ocr/ .
You must be able to invoke the tesseract command as "tesseract". If this
isn't the case,for example because tesseract isn't in your PATH,you will
have to change the "tesseract_cmd" variable at the top of 'tesseract.py'.
Under Debian/Ubuntu you can use the package "tesseract-ocr".

Installing via pip:

See the [PyTesseract package page](https://pypi.python.org/pypi/PyTesseract)
```
$> sudo pip install PyTesseract

翻译一下:

a、Python-tesseract支持python2.5及更高版本;

b、Python-tesseract需要安装PIL(Python Imaging Library) ,来支持更多的图片格式;

c、Python-tesseract需要安装tesseract-ocr安装包。

综上,PyTesseract原理:

1、上一篇博文中提到,执行命令行 tesseract.exe 1.png output -l eng ,可以识别1.png中文字,并把识别结果输出到output.txt中;

2、PyTesseract对上述过程进行了二次封装,自动调用tesseract.exe,并读取output.txt文件内容,作为函数的返回值进行返回。

二、PyTesseract使用

USAGE:
```
> try:
> import Image
> except ImportError:
> from PIL import Image
> import PyTesseract
> print(PyTesseract.image_to_string(Image.open('test.png')))
> print(PyTesseract.image_to_string(Image.open('test-european.jpg'),lang='fra'))

可以看到:

1、核心代码就是image_to_string函数,该函数支持-l eng 参数,支持-psm 参数。

用法

image_to_string(Image.open('test.png'),lang="eng" config="-psm 7")

2、PyTesseract里调用了image,所以才需要PIL,其实tesseract.exe本身是支持jpeg、png等图片格式的。

实例代码,识别某公共网站的验证码(大家千万别干坏事啊,思虑再三,最后还是隐掉网站域名,大家去找别的网站试试吧……):

#-*-coding=utf-8-*-
__author__='zhongtang'

import urllib
import urllib2
import cookielib
import math
import random
import time
import os
import htmltool
from PyTesseract import *
from PIL import Image
from PIL import ImageEnhance
import re

class orclnypcg:
  def __init__(self):
    self.baseUrl='http://jbywcg.****.com.cn'
    self.ht=htmltool.htmltool()
    self.curPath=self.ht.getPyFileDir()
    self.authCode=''
    
  def initUrllib2(self):
    try:
      cookie = cookielib.CookieJar()
      cookieHandLer = urllib2.HTTPCookieProcessor(cookie)
      httpHandLer=urllib2.HTTPHandler(debuglevel=0)
      httpsHandLer=urllib2.HTTPSHandler(debuglevel=0)
    except:
      raise
    else:
       opener = urllib2.build_opener(cookieHandLer,httpHandLer,httpsHandLer)
       opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML,like Gecko) Chrome/23.0.1271.64 Safari/537.11')]
       urllib2.install_opener(opener)
       
  def urllib2Navigate(self,url,data={}):      #定义连接函数,有超时重连功能
    tryTimes = 0
    while True:
      if (tryTimes>20):
        print u"多次尝试仍无法链接网络,程序终止"
        break
      try:
        if (data=={}):
          req = urllib2.Request(url)
        else:
          req = urllib2.Request(url,urllib.urlencode(data))
        response =urllib2.urlopen(req)
        bodydata = response.read()
        headerdata = response.info()
        if headerdata.get('content-encoding')=='gzip':
          rdata = StringIO.StringIO(bodydata)
          gz = gzip.GzipFile(fileobj=rdata)
          bodydata = gz.read()
          gz.close()
        tryTimes = tryTimes +1
      except urllib2.HTTPError,e:
       print 'HTTPError[%s]\n' %e.code        
      except urllib2.URLError,e:
       print 'URLError[%s]\n' %e.reason  
      except socket.error:
        print u"连接失败,尝试重新连接"
      else:
        break
    return bodydata,headerdata
  
  def randomCodeOcr(self,filename):
    image = Image.open(filename)
    #使用ImageEnhance可以增强图片的识别率
    #enhancer = ImageEnhance.Contrast(image)
    #enhancer = enhancer.enhance(4)
    image = image.convert('L')
    ltext = ''
    ltext= image_to_string(image)
    #去掉非法字符,只保留字母数字
    ltext=re.sub("\W","",ltext)
    print u'[%s]识别到验证码:[%s]!!!' %(filename,ltext)
    image.save(filename)
    #print ltext
    return ltext

  def getRandomCode(self):
    #开始获取验证码
    #http://jbywcg.****.com.cn/CommonPage/Code.aspx?0.9409255818463862
    i = 0 
    while ( i<=100):
      i += 1 
      #拼接验证码Url
      randomUrlNew='%s/CommonPage/Code.aspx?%s' %(self.baseUrl,random.random())
      #拼接验证码本地文件名
      filename= '%s.png' %(i)
      filename= os.path.join(self.curPath,filename)
      jpgdata,jpgheader = self.urllib2Navigate(randomUrlNew)
      if len(jpgdata)<= 0 :
        print u'获取验证码出错!\n'
        return False
      f = open(filename,'wb')
      f.write(jpgdata)
      #print u"保存图片:",fileName
      f.close()
      self.authCode = self.randomCodeOcr(filename)


#主程序开始
orcln=orclnypcg()
orcln.initUrllib2()
orcln.getRandomCode()

三、PyTesseract代码优化

上述程序在windows平台运行时,会发现有黑色的控制台窗口一闪而过的画面,不太友好。

略微修改PyTesseract.py(C:\Python27\Lib\site-packages\PyTesseract目录下),把上述过程进行了隐藏。

# modified by zhongtang hide console window
# new code
IS_WIN32 = 'win32' in str(sys.platform).lower()
if IS_WIN32:
   startupinfo = subprocess.STARTUPINFO()
   startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
   startupinfo.wShowWindow = subprocess.SW_HIDE
   proc = subprocess.Popen(command,
        stderr=subprocess.PIPE,startupinfo=startupinfo)
'''
# old code
proc = subprocess.Popen(command,
   stderr=subprocess.PIPE)
'''
# modified end

为了方便初学者,把PyTesseract.py也贴出来,高手自行忽略。

#!/usr/bin/env python
'''
Python-tesseract is an optical character recognition (OCR) tool for python.
That is,it will recognize and "read" the text embedded in images.

Python-tesseract is a wrapper for google's Tesseract-OCR
( http://code.google.com/p/tesseract-ocr/ ). It is also useful as a
stand-alone invocation script to tesseract,as it can read all image types
supported by the Python Imaging Library,and others,whereas tesseract-ocr by default only supports tiff and bmp.
Additionally,Python-tesseract will print the recognized
text in stead of writing it to a file. Support for confidence estimates and
bounding Box data is planned for future releases.


USAGE:
```
 > try:
 >   import Image
 > except ImportError:
 >   from PIL import Image
 > import PyTesseract
 > print(PyTesseract.image_to_string(Image.open('test.png')))
 > print(PyTesseract.image_to_string(Image.open('test-european.jpg'),lang='fra'))
```

INSTALLATION:

Prerequisites:
* Python-tesseract requires python 2.5 or later or python 3.
* You will need the Python Imaging Library (PIL). Under Debian/Ubuntu,this is
 the package "python-imaging" or "python3-imaging" for python3.
* Install google tesseract-ocr from http://code.google.com/p/tesseract-ocr/ .
 You must be able to invoke the tesseract command as "tesseract". If this
 isn't the case,you will
 have to change the "tesseract_cmd" variable at the top of 'tesseract.py'.
 Under Debian/Ubuntu you can use the package "tesseract-ocr".
 
Installing via pip:  
See the [PyTesseract package page](https://pypi.python.org/pypi/PyTesseract)   
$> sudo pip install PyTesseract  

Installing from source:  
$> git clone git@github.com:madmaze/PyTesseract.git  
$> sudo python setup.py install  


LICENSE:
Python-tesseract is released under the GPL v3.

CONTRIBUTERS:
- Originally written by [Samuel Hoffstaetter](https://github.com/hoffstaetter) 
- [Juarez Bochi](https://github.com/jbochi)
- [Matthias Lee](https://github.com/madmaze)
- [lars Kistner](https://github.com/Sr4l)

'''

# CHANGE THIS IF TESSERACT IS NOT IN YOUR PATH,OR IS NAMED DIFFERENTLY
tesseract_cmd = 'tesseract'

try:
  import Image
except ImportError:
  from PIL import Image
import subprocess
import sys
import tempfile
import os
import shlex

__all__ = ['image_to_string']

def run_tesseract(input_filename,output_filename_base,lang=None,Boxes=False,config=None):
  '''
  runs the command:
    `tesseract_cmd` `input_filename` `output_filename_base`
  
  returns the exit status of tesseract,as well as tesseract's stderr output

  '''
  command = [tesseract_cmd,input_filename,output_filename_base]
  
  if lang is not None:
    command += ['-l',lang]

  if Boxes:
    command += ['batch.nochop','makeBox']
    
  if config:
    command += shlex.split(config)
    
  # modified by zhongtang hide console window
  # new code
  IS_WIN32 = 'win32' in str(sys.platform).lower()
  if IS_WIN32:
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = subprocess.SW_HIDE
  proc = subprocess.Popen(command,stderr=subprocess.PIPE,startupinfo=startupinfo)
  '''
  # old code
  proc = subprocess.Popen(command,stderr=subprocess.PIPE)
  '''
  # modified end
  
  return (proc.wait(),proc.stderr.read())

def cleanup(filename):
  ''' tries to remove the given filename. Ignores non-existent files '''
  try:
    os.remove(filename)
  except OSError:
    pass

def get_errors(error_string):
  '''
  returns all lines in the error_string that start with the string "error"

  '''

  lines = error_string.splitlines()
  error_lines = tuple(line for line in lines if line.find('Error') >= 0)
  if len(error_lines) > 0:
    return '\n'.join(error_lines)
  else:
    return error_string.strip()

def tempnam():
  ''' returns a temporary file-name '''
  tmpfile = tempfile.NamedTemporaryFile(prefix="tess_")
  return tmpfile.name

class TesseractError(Exception):
  def __init__(self,status,message):
    self.status = status
    self.message = message
    self.args = (status,message)

def image_to_string(image,config=None):
  '''
  Runs tesseract on the specified image. First,the image is written to disk,and then the tesseract command is run on the image. Resseract's result is
  read,and the temporary files are erased.
  
  also supports Boxes and config.
  
  if Boxes=True
    "batch.nochop makeBox" gets added to the tesseract call
  if config is set,the config gets appended to the command.
    ex: config="-psm 6"

  '''

  if len(image.split()) == 4:
    # In case we have 4 channels,lets discard the Alpha.
    # Kind of a hack,should fix in the future some time.
    r,g,b,a = image.split()
    image = Image.merge("RGB",(r,b))
  
  input_file_name = '%s.bmp' % tempnam()
  output_file_name_base = tempnam()
  if not Boxes:
    output_file_name = '%s.txt' % output_file_name_base
  else:
    output_file_name = '%s.Box' % output_file_name_base
  try:
    image.save(input_file_name)
    status,error_string = run_tesseract(input_file_name,output_file_name_base,lang=lang,Boxes=Boxes,config=config)
    if status:
      #print 'test',error_string
      errors = get_errors(error_string)
      raise TesseractError(status,errors)
    f = open(output_file_name)
    try:
      return f.read().strip()
    finally:
      f.close()
  finally:
    cleanup(input_file_name)
    cleanup(output_file_name)

def main():
  if len(sys.argv) == 2:
    filename = sys.argv[1]
    try:
      image = Image.open(filename)
      if len(image.split()) == 4:
        # In case we have 4 channels,lets discard the Alpha.
        # Kind of a hack,should fix in the future some time.
        r,a = image.split()
        image = Image.merge("RGB",b))
    except IOError:
      sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
      exit(1)
    print(image_to_string(image))
  elif len(sys.argv) == 4 and sys.argv[1] == '-l':
    lang = sys.argv[2]
    filename = sys.argv[3]
    try:
      image = Image.open(filename)
    except IOError:
      sys.stderr.write('ERROR: Could not open file "%s"\n' % filename)
      exit(1)
    print(image_to_string(image,lang=lang))
  else:
    sys.stderr.write('Usage: python PyTesseract.py [-l language] input_file\n')
    exit(2)

if __name__ == '__main__':
  main()

以上……

以上这篇python下调用PyTesseract识别某网站验证码的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程小技巧。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用爬虫利器 Playwright,轻松爬取抖查查数据 我们先分析登录的接口,其中 url 有一些非业务参数:ts、he、sign、secret。 然后根据这些参数作为关键词,定位到相关的 js 代码。 最后,逐步进行代码的跟踪,发现大部分的代码被混淆加密了。 花费了大半天,来还原这些混淆加密的代码
轻松爬取灰豚数据的抖音商品数据 调用两次登录接口实现模拟登录 我们分析登录接口,发现调用了两次不同的接口;而且,需要先调用 https://login.huitun.com/weChat/userLogin,然后再调用 https://dyapi.huitun.com/userLogin 接口。 登
成功绕过阿里无痕验证码,一键爬取飞瓜数据 飞瓜数据的登录接口,接入了阿里云的无痕验证码;通过接口方式模拟登录,难度比较高。所以,我们使用自动化的方式来实现模拟登录,并且获取到 cookie 数据。 [阿里无痕验证码] https://help.aliyun.com/document_detail/1
一文教你从零开始入门蝉妈妈数据爬取,成功逆向破解数据加密算法 通过接口进行模拟登录 我们先通过正常登录的方式,分析对应的登录接口。通过 F12 打开谷歌浏览器的调试面板,可以看到登录需要传递的一些参数;其中看到密码是被加密了。 不过我们通过经验可以大概猜测一下,应该是通过 md5 算法加密了。 接下
抽丝剥茧成功破解红人点集的签名加密算法 抽丝剥茧破解登录签名算法,成功实现模拟登录 headers = {} phone_num = &quot;xxxx&quot; password = &quot;xxxx&quot; md5_hash = hashlib.md5() md5_hash.upda
轻松绕过 Graphql 接口爬取有米有数的商品数据 有米有数数据的 API 接口,使用的是一种 API 查询语言 graphql。所有的 API 只有一个入口,具体的操作隐藏在请求数据体里面传输。 模拟登录,获取 sessionId 调用登录接口,进行模拟登录。 cookies = {} head
我最近重新拾起了计算机视觉,借助Python的opencv还有face_recognition库写了个简单的图像识别demo,额外定制了一些内容,原本想打包成exe然后发给朋友,不过在这当中遇到了许多小问题,都解决了,记录一下踩过的坑。 1、Pyinstaller打包过程当中出现warning,跟d
说到Pooling,相信学习过CNN的朋友们都不会感到陌生。Pooling在中文当中的意思是“池化”,在神经网络当中非常常见,通常用的比较多的一种是Max Pooling,具体操作如下图: 结合图像理解,相信你也会大概明白其中的本意。不过Pooling并不是只可以选取2x2的窗口大小,即便是3x3,
记得大一学Python的时候,有一个题目是判断一个数是否是复数。当时觉得比较复杂不好写,就琢磨了一个偷懒的好办法,用异常处理的手段便可以大大程度帮助你简短代码(偷懒)。以下是判断整数和复数的两段小代码: 相信看到这里,你也有所顿悟,能拓展出更多有意思的方法~
文章目录 3 直方图Histogramplot1. 基本直方图的绘制 Basic histogram2. 数据分布与密度信息显示 Control rug and density on seaborn histogram3. 带箱形图的直方图 Histogram with a boxplot on t