首頁  >  文章  >  後端開發  >  python入門之識別驗證碼介紹

python入門之識別驗證碼介紹

高洛峰
高洛峰原創
2017-03-06 11:28:291430瀏覽

前言

驗證碼?我也能破解?

關於驗證碼的介紹就不多說了,各種各樣的驗證碼在人們生活中時不時就會冒出來,身為學生日常接觸最多的就是教務處系統的驗證碼了,例如如下的驗證碼:

python入門之識別驗證碼介紹

#識別辦法

模擬登陸有著複雜的步驟,在這裡咱們不管其他操作,只負責根據輸入的一張驗證碼圖片返回一個答案字串。

我們知道驗證碼為了製作幹擾,會把圖片弄成五顏六色的樣子,而我們首先就是要去除這些幹擾,這一步就需要不斷試驗了,增強圖片色彩,加大對比度等等都可以產生幫助。

python入門之識別驗證碼介紹

python入門之識別驗證碼介紹

在經過各種對圖片的操作之後,終於找到了比較完美的去除乾擾方案。可以看到在去除乾擾之後,最優情況下,我們將得到一張十分純淨的黑白字元圖片。一張圖片上有四個字符,沒辦法一下子就把四個字符全部識別,需要把圖片進行裁剪,裁剪成每張小圖只有一個字符的樣子,再對每張圖片分別進行識別。

#接下來就是辨識文字了,我們首先把得到的小圖轉換成01表示的矩陣,每個矩陣代表一個字元。

例如數字六的矩陣

num_6=[
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,1,1,0,0,0,0,0,0,
0,0,0,0,1,1,1,0,0,0,0,0,0,
0,0,0,1,1,1,0,0,0,0,0,0,0,
0,0,0,1,1,0,0,0,0,0,0,0,0,
0,0,1,1,0,0,0,0,0,0,0,0,0,
0,0,1,1,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,1,0,0,0,0,0,
0,1,1,1,1,1,1,1,1,0,0,0,0,
0,1,1,0,0,0,0,1,1,1,0,0,0,
0,1,1,0,0,0,0,0,1,1,0,0,0,
0,1,1,0,0,0,0,0,1,1,0,0,0,
0,1,1,1,0,0,0,1,1,1,0,0,0,
0,0,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,1,1,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,
]

#遠遠望過去,瞇著眼睛還是能分辨出來的。

因為驗證碼十分規整,每個數字所在的位置都是固定的,所以並不需要涉及什麼機器學習的演算法,只是簡單的進行一下矩陣的比對就可以了,在所有的實現做好的矩陣中找到相似度最高的矩陣就可以了,在這裡的比對方法多種多樣,反正數據簡單能正確識別出來就好。

至此,咱們的驗證碼辨識工作就結束了。

這次進行的驗證碼識別主要採用python的PIL進行圖片操作,模擬登陸自動填入驗證碼的全部程式碼請看這裡:

##範例程式碼

# -*- coding: utf-8 -*
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
import re
import requests
import io
import os
import json
from PIL import Image
from PIL import ImageEnhance
from bs4 import BeautifulSoup

import mdata

class Student:
 def __init__(self, user,password):
  self.user = str(user)
  self.password = str(password)
  self.s = requests.Session()

 def login(self):
  url = "http://202.118.31.197/ACTIONLOGON.APPPROCESS?mode=4"
  res = self.s.get(url).text
  imageUrl = &#39;http://202.118.31.197/&#39;+re.findall(&#39;<img src="(.+?)" width="55"&#39;,res)[0]
  im = Image.open(io.BytesIO(self.s.get(imageUrl).content))
  enhancer = ImageEnhance.Contrast(im)
  im = enhancer.enhance(7)
  x,y = im.size
  for i in range(y):
   for j in range(x):
    if (im.getpixel((j,i))!=(0,0,0)):
     im.putpixel((j,i),(255,255,255))
  num = [6,19,32,45]
  verifyCode = ""
  for i in range(4):
   a = im.crop((num[i],0,num[i]+13,20))
   l=[]
   x,y = a.size
   for i in range(y):
    for j in range(x):
     if (a.getpixel((j,i))==(0,0,0)):
      l.append(1)
     else:
      l.append(0)
   his=0
   chrr="";
   for i in mdata.data:
    r=0;
    for j in range(260):
     if(l[j]==mdata.data[i][j]):
      r+=1
    if(r>his):
     his=r
     chrr=i
   verifyCode+=chrr
   # print "辅助输入验证码完毕:",verifyCode
  data= {
  &#39;WebUserNO&#39;:str(self.user),
  &#39;Password&#39;:str(self.password),
  &#39;Agnomen&#39;:verifyCode,
  }
  url = "http://202.118.31.197/ACTIONLOGON.APPPROCESS?mode=4"
  t = self.s.post(url,data=data).text
  if re.findall("images/Logout2",t)==[]:
   l = &#39;[0,"&#39;+re.findall(&#39;alert((.+?));&#39;,t)[1][1][2:-2]+&#39;"]&#39;+" "+self.user+" "+self.password+"\n"
   # print l
   # return &#39;[0,"&#39;+re.findall(&#39;alert((.+?));&#39;,t)[1][1][2:-2]+&#39;"]&#39;
   return [False,l]
  else:
   l = &#39;登录成功 &#39;+re.findall(&#39;! (.+?) &#39;,t)[0]+" "+self.user+" "+self.password+"\n"
   # print l
   return [True,l]

 def getInfo(self):
  imageUrl = &#39;http://202.118.31.197/ACTIONDSPUSERPHOTO.APPPROCESS&#39;
  data = self.s.get(&#39;http://202.118.31.197/ACTIONQUERYBASESTUDENTINFO.APPPROCESS?mode=3&#39;).text #学籍信息
  data = BeautifulSoup(data,"lxml")
  q = data.find_all("table",attrs={&#39;align&#39;:"left"})
  a = []
  for i in q[0]:
   if type(i)==type(q[0]) :
    for j in i :
     if type(j) ==type(i):
      a.append(j.text)
  for i in q[1]:
   if type(i)==type(q[1]) :
    for j in i :
     if type(j) ==type(i):
      a.append(j.text)
  data = {}
  for i in range(1,len(a),2):
   data[a[i-1]]=a[i]
  # data[&#39;照片&#39;] = io.BytesIO(self.s.get(imageUrl).content)
  return json.dumps(data)

 def getPic(self):
  imageUrl = &#39;http://202.118.31.197/ACTIONDSPUSERPHOTO.APPPROCESS&#39;
  pic = Image.open(io.BytesIO(self.s.get(imageUrl).content))
  return pic

 def getScore(self):
   score = self.s.get(&#39;http://202.118.31.197/ACTIONQUERYSTUDENTSCORE.APPPROCESS&#39;).text #成绩单
   score = BeautifulSoup(score, "lxml")
   q = score.find_all(attrs={&#39;height&#39;:"36"})[0]
   point = q.text
   print point[point.find(&#39;平均学分绩点&#39;):]
   table = score.html.body.table
   people = table.find_all(attrs={&#39;height&#39; : &#39;36&#39;})[0].string
   r = table.find_all(&#39;table&#39;,attrs={&#39;align&#39; : &#39;left&#39;})[0].find_all(&#39;tr&#39;)
   subject = []
   lesson = []
   for i in r[0]:
    if type(r[0])==type(i):
     subject.append(i.string)
   for i in r:
    k=0
    temp = {}
    for j in i:
     if type(r[0])==type(j):
      temp[subject[k]] = j.string
      k+=1
    lesson.append(temp)
   lesson.pop()
   lesson.pop(0)
   return json.dumps(lesson)

 def logoff(self):
  return self.s.get(&#39;http://202.118.31.197/ACTIONLOGOUT.APPPROCESS&#39;).text

if __name__ == "__main__":
 a = Student(20150000,20150000)
 r = a.login()
 print r[1]
 if r[0]:
  r = json.loads(a.getScore())
  for i in r:
   for j in i:
    print i[j],
   print
  q = json.loads(a.getInfo())
  for i in q:
   print i,q[i]
  a.getPic().show()
 a.logoff()

更多python入門之識別驗證碼介紹相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn