新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

python验证码函数 python获取验证码

如何利用Python做简单的验证码识别

先是获取验证码样本。。。我存了大概500个。

创新互联建站专注为客户提供全方位的互联网综合服务,包含不限于网站设计、网站建设、阳新网络推广、小程序开发、阳新网络营销、阳新企业策划、阳新品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联建站为所有大学生创业者提供阳新建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

用dia测了测每个字之间的间距,直接用PIL开始切。

from PIL import Image

for j in range(0,500):

f=Image.open("../test{}.jpg".format(j))

for i in range(0,4):

f.crop((20+20*i,0,40+20*i,40)).save("test{0}-{1}.jpg".format(j,i+1))

上面一段脚本的意思是把jpg切成四个小块然后保存

之后就是二值化啦。

def TotallyShit(im):

x,y=im.size

mmltilist=list()

for i in range(x):

for j in range(y):

if im.getpixel((i,j))200:

mmltilist.append(1)

else:

mmltilist.append(0)

return mmltilist

咳咳,不要在意函数的名字。上面的一段代码的意思是遍历图片的每个像素点,颜色数值小于200的用1表示,其他的用0表示。

其中的im代表的是Image.open()类型。

切好的图片长这样的。

只能说这样切的图片还是很粗糙,很僵硬。

下面就是分类啦。

把0-9,“+”,”-“的图片挑好并放在不同的文件夹里面,这里就是纯体力活了。

再之后就是模型建立了。

这里我试了自己写的还有sklearn svm和sklearn neural_network。发现最后一个的识别正确率高的多。不知道是不是我样本问题QAQ。

下面是模型建立的代码

from sklearn.neural_network import MLPClassifier

import numpy as np

def clf():

clf=MLPClassifier()

mmltilist=list()

X=list()

for i in range(0,12):

for j in os.listdir("douplings/douplings-{}".format(i)):

mmltilist.append(TotallyShit(Image.open("douplings/douplings-{0}/{1}".format(i,j)).convert("L")))

X.append(i)

clf.fit(mmltilist,X)

return clf

大概的意思是从图片源中读取图片和label然后放到模型中去跑吧。

之后便是图像匹配啦。

def get_captcha(self):

with open("test.jpg","wb") as f:

f.write(self.session.get(self.live_captcha_url).content)

gim=Image.open("test.jpg").convert("L")

recognize_list=list()

for i in range(0,4):

part=TotallyShit(gim.crop((20+20*i,0,40+20*i,40)))

np_part_array=np.array(part).reshape(1,-1)

predict_num=int(self.clf.predict(np_part_array)[0])

if predict_num==11:

recognize_list.append("+")

elif predict_num==10:

recognize_list.append("-")

else:

recognize_list.append(str(predict_num))

return ''.join(recognize_list)

最后eval一下识别出来的字符串就得出结果了。。

顺便提一句现在的bilibili登陆改成rsa加密了,麻蛋,以前的脚本全部作废,心好痛。

登陆的代码。

import time

import requests

import rsa

r=requests.session()

data=r.get("act=getkey_="+str(int(time.time()*1000))).json()

pub_key=rsa.PublicKey.load_pkcs1_openssl_pem(data['key'])

payload = {

'keep': 1,

'captcha': '',

'userid': "youruserid",

'pwd': b64encode(rsa.encrypt((data['hash'] +"yourpassword").encode(), pub_key)).decode(),

}

r.post("",data=payload)

python爬验证码

1.找地址

首先,我们要找到这个网站生成验证码的地址,这个地址我们可以通过查看他的源代码来实现。

1.找地址

首先,我们要找到这个网站生成验证码的地址,这个地址我们可以通过查看他的源代码来实现。

就以某大学教务网为例,这个教务网的模板很多学校都在采用:

我就截取表单的验证码部分即可。

td align="center" rowspan="3" 

img  id="imgCode" src="../sys/ValidateCode.aspx" 

onclick="changeValidateCode(this)" alt="单击可更换图片!" 

style="CURSOR: pointer;"

br看不清,则单击图片!                                 

/td123456123456

这里就可以知道,地址就是../sys/ValidateCode.aspx

组合一下地址就是

也就是我们等一下要用到的地址了。

我们可以查看一下那个网页。

2.处理图片

去查看了一下那个地址

果不其然,都是乱码,因为验证码分为两种。

1)直接处理成JPG/GIF/PNG或者其他格式,然后直接读取到一个图片地址。

2)接收用户触发,然后生成,再直接处理成图像,不读取到一个图片地址。

我们这里是第二种,我们要自己来读取他,到本地,再手动输入验证码。

# -*- coding: utf-8 -*-

import urllib2

#验证码的处理#

#验证码生成页面的地址#

im_url = ''

#读取验证码图片#

im_data = urllib2.urlopen(im_url).read()

#打开一个Code.PNG文件在D盘,没有的话自动生成#

f=open('d:\\Code.png','wb')

#写入图片内容#

f.write(im_data)

#关闭文件#

f.close()1234567891011121312345678910111213

这里包括两个部分:

1)打开那个生成验证码图片的页面,读取

2)将读取到的内容,保存成图片,下载到本地

我们这里的地址是可以随便写的,保存在你想保存的地方。

到这里我们就完成了验证码的一小部分。

by–LoDog

希望能帮到你!

Python 设计一个函数产生指定长度的验证码 length = len(base_str) - 1 ,这里为什么会减 1????

random.randint()

取的数的区间是前后封闭的。也就是可能会取到last_pos

如果不减1那么就会出错的。

all_chars[len(all_chars)]就出错了。

python怎样调用第三方平台识别验证码

一、pytesseract介绍

1、pytesseract说明

pytesseract最新版本0.1.6,网址:h

Python-tesseract is a wrapper for google's Tesseract-OCR

( ht-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 hsseract-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](hi/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'),))

可以看到:

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等图片格式的。

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

View Code

三、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也贴出来,高手自行忽略。

View Code


新闻名称:python验证码函数 python获取验证码
当前地址:http://www.wjwzjz.com/article/dodehdh.html
在线咨询
服务热线
服务热线:028-86922220
TOP