Home Backend Development Python Tutorial Detailed explanation of code for python recognition verification code

Detailed explanation of code for python recognition verification code

May 08, 2017 pm 04:06 PM
python Verification code

This article mainly introduces the relevant information on identifying verification codes in python. This is a basic introductory tutorial for learning python. The introduction in the article is very detailed. A complete sample code is also given at the end of the article. Friends who need it can refer to it. , let’s take a look below.

Preface

Verification code? Can I crack it too?

I won’t say much about the introduction of verification codes. Various verification codes appear from time to time in people’s lives. As a student, the one you come into contact with most every day is the system of the Academic Affairs Office. Verification code, such as the following verification code:

Identification method

Simulated login has complicated steps. Here we ignore other operations and are only responsible for returning an answer string based on the input verification code picture.

We know that the verification code will make the picture colorful in order to create interference, and we first need to remove these interferences. This step requires continuous experimentation, enhancing the color of the picture, increasing the contrast, etc. can help.

After various operations on the pictures, I finally found a more perfect solution for removing interference. It can be seen that after removing the interference, under optimal circumstances, we will get a very pure black and white character picture. There are four characters in a picture. It is impossible to recognize all four characters at once. The picture needs to be cropped so that each small picture has only one character, and then each picture is recognized separately.

#The next step is to recognize the text, we First, convert the obtained small picture into a matrix represented by 01, each matrix represents a character.


For example, the matrix of the number six

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,
]
Copy after login

Looking at it from a distance, you can still distinguish it if you squint.


Because the verification code is very regular and the position of each number is fixed, there is no need to involve any machine learning algorithm. It is just a simple comparison of the matrices. Just find the matrix with the highest similarity among all the implemented matrices. There are various comparison methods here. Anyway, as long as the data is simple and can be correctly identified.

At this point, our verification code identification work is over.

The verification code recognition carried out this time mainly uses python's PIL for image manipulation. Please see here for all the codes to simulate login and automatically fill in the verification code:

Sample code

# -*- 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()
Copy after login

【Related recommendations】


1.

Python free video tutorial

2.

Object-oriented video tutorial

3.

Python Learning Manual

The above is the detailed content of Detailed explanation of code for python recognition verification code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

Can mysql workbench connect to mariadb Can mysql workbench connect to mariadb Apr 08, 2025 pm 02:33 PM

MySQL Workbench can connect to MariaDB, provided that the configuration is correct. First select "MariaDB" as the connector type. In the connection configuration, set HOST, PORT, USER, PASSWORD, and DATABASE correctly. When testing the connection, check that the MariaDB service is started, whether the username and password are correct, whether the port number is correct, whether the firewall allows connections, and whether the database exists. In advanced usage, use connection pooling technology to optimize performance. Common errors include insufficient permissions, network connection problems, etc. When debugging errors, carefully analyze error information and use debugging tools. Optimizing network configuration can improve performance

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

How to solve mysql cannot connect to local host How to solve mysql cannot connect to local host Apr 08, 2025 pm 02:24 PM

The MySQL connection may be due to the following reasons: MySQL service is not started, the firewall intercepts the connection, the port number is incorrect, the user name or password is incorrect, the listening address in my.cnf is improperly configured, etc. The troubleshooting steps include: 1. Check whether the MySQL service is running; 2. Adjust the firewall settings to allow MySQL to listen to port 3306; 3. Confirm that the port number is consistent with the actual port number; 4. Check whether the user name and password are correct; 5. Make sure the bind-address settings in my.cnf are correct.

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

See all articles