首页 编程教程正文

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

piaodoo 编程教程 2020-02-02 12:39:01 973 0 python教程

下面小编就为大家带来一篇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, 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.


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, 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  

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, lang=None, boxes=False, 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, g, 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' , status,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, g, b, a = image.split()
        image = Image.merge("RGB", (r, g, 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识别某网站验证码的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/2816.html

评论

搜索

游戏网站源码,织梦网站源码,wordpress,wordpress主题,wordpress下载,wordpress插件,wordpress.com,wordpress模板,wordpress教程,wordpress 主题,wordpress安装,wordpress 模板,wordpress 插件,wordpress主题下载,wordpress企业主题,wordpress seo,wordpress主题开发,wordpress theme,wordpress论坛,wordpress 企业主题,wordpress主机,wordpress中文主题,wordpress cms主题,wordpress plugin,wordpress 主题下载,wordpress 主机,wordpress空间,wordpress mu,wordpress 模版,wordpress汉化主题,wordpress淘宝客主题,wordpress 空间,wordpress代码,WORDPRESS HOSTING,wordpress优点,wordpress安卓客户端,wordpress技巧,wordpress换空间,wordpress themes,网站模板,ppt模板网站,模板网站,企业网站模板,网站设计模板,免费网站模板,个人网站模板,ppt模板下载网站,网站模板下载,公司网站模板,门户网站模板,学校网站模板,网站首页模板,网站模板免费下载,旅游网站模板,网站后台模板,免费网站模板下载,传奇网站模板,网站建设模板,外贸网站模板,网站 模板,个人主页网站模板,个人网站模板下载,政府网站模板,音乐网站模板,导航网站模板,免费企业网站模板,企业网站模板下载,手表网站模板,韩国网站模板,汽车网站模板,教育网站模板,网站后台管理模板,班级网站模板,新闻网站模板,房产中介网站模板,旅游网站模板下载,工艺品网站模板,电子商务网站模板,旅游网站设计模板,团购网站模板,flash网站模板,个人网站设计模板,婚庆网站模板,广告公司网站模板,商业网站模板,手机网站模板,免费模板网站推荐,ppt免费模板网站推荐,织梦网站模板,html网站模板建站,网站html模板,免费个人网站模板,公司网站源码,sns源码,彩票网站源码,周易网站源码,源码基地,交友源码,学校网站源码,asp.net 源码,源码天下,jsp网站源码,论坛源码下载,广告联盟源码,建站源码,delphi源码,源码爱好者,酷源码,net源码,源码超市,医疗网站源码,flash源码,搜源码,源码程序,dede源码,新闻网站源码,易语言源码大全,旅游网站源码下载,flash 源码,免费源码论坛,android游戏源码,电脑维修网站源码,30源码网,股票软件源码,卖源码,源码教程,安居客 源码,vip源码,家教源码,.net源码下载,Web源码,网络公司源码,佛教网站源码,android源码学习,房产源码,钓鱼网站源码,775源码屋,web游戏源码,成品网站 源码78w78不用下载,h5游戏网站源码,asp网站源码下载,webgame源码,电子商务网站源码,vb.net源码,乐嘿源码,8a商业源码论坛,fbreader源码,在线客服系统 源码,google源码,.net网站源码,快递查询源码,源码搜藏网,dede整站源码,周易 源码,52源码论坛,财经网站源码,织梦下载站源码,qq钓鱼网站源码,flash游戏源码,房产网源码,源码搜搜,电子商务源码,团购网站源码,团购网源码,jsp源码下载,jsp源码,h站源码,8a源码,婚纱摄影网站源码,易语言盗号源码,x站源码,qq空间psd源码,免费商业源码,笑话网站源码,源码集合,源码家园,啊哦源码,星期六源码,源码熊,阿奇源码,百分百源码网,一手日源码资源,旅行网站源码,b站工程源码泄露,新站长源码,8a商业源码,asp论坛源码,flash源码下载,404源码社区,创业网站源码,php网页源码,易支付源码,成品网站w灬源码,免费CMS成品网站源码,成品网站W灬源码1688仙踪林,成品APP短视频源码下载网站,成品网站源码1688可靠吗,免费B2B网站源码,成品APP直播源码下载,国外儿童网站源码在线,成品网站W灬源码1688,源码,成品网站w灬 源码1688,免费源码网站都有哪些,成品网站源码78W78隐藏通道1,网站源码,源码网,源码网站,源码时代,源码之家,源码下载,php源码,易语言源码,源码论坛,源码是什么,商城源码,论坛源码,源码交易,源码站,源码库,免费源码,免费网站ja**源码大全,ja**源码,成品网站w灬源码1377,a5源码,站长源码,成品网站源码78W78隐藏通道1APP,源码分享,网站源码下载,源码中国,asp源码,源码社区,企业网站源码,php源码下载,成品app直播源码搭建,在线观看视频网站源码2021,旅游网站源码,安卓源码,通达信选股公式源码,神马影院php源码,c#源码,成品网站w灬源码1688网页,php 源码,网页游戏源码,android源码下载,源码吧,视频源码大全,成品短视频APP源码搭建,asp源码下载,私服源码,电脑维修源码,个人主页源码,源码出售,php网站源码,刀客源码,网址导航源码,导航网站源码,源码天空,asp 源码,软件源码,精品源码,成品网站源码1688自动跳转,个人网站源码,源码哥,在线考试系统源码,cms源码,c# 源码,商业源码,vb源码,门户网站源码,音乐网站源码,中国源码,安卓源码下载,asp网站源码,在线客服源码,电影网站源码,免费源码下载,整站源码,源码交易网,易语言源码网,.net源码,在线客服系统源码,淘客源码,卡盟源码,网站源码出售,vb源码下载,莎莎源码,熊猫烧香源码,asp.net源码,商业源码网,外贸网站源码,61源码网,zblog模板,zblog企业模板,帝国cms模板,帝国cms插件,discuz模板