前一段时间爬取一些网页数据需要获取其的验证码,然后拼接url获取数据。然后通过看其验证码形式,就是一些简单的字母加数字,然后加燥的验证码。然后网上百度了一下,Python可以做一些简单的验证码破解。具体操作如下:
一:windows安装相应的包:
1.先安装Pillow:pip install Pillow
2.安装tesseract-ocr:安装的下载地址:https://ask.hellobi.com/blog/tangyudi/(引用的链接地址)
3.安装pytesseract: pip install pytesseract
tesseract_cmd=r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe'
请根据这个链接进行安装:http://blog.csdn.net/diandianxiyu_geek/article/details/50522582(引用的网址)
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import urllib
from PIL import Image,ImageEnhance
import pytesseract
import requests
import time
import re
from lxml import etree
from PublicCode import search_config
# 破解验证码
t =int(round(time.time()*1000))
def get_guid(t,second_header):
url='http://cri.gz.gov.cn/Search/NewGuid?t=%s'%t
result =requests.get(url,search_config.second_header)
return result.content
def get_image(guid):
url='http://cri.gz.gov.cn/Search/ValidateCode?t=1517210875615&guid=%s'%guid
res = requests.get(url)
with open('1.jpg',"wb") as f:
f.write(res.content)
res = Image.open('1.jpg')
return res
threshold = 150
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
def getverify1(name):
im = Image.open(name)
imgry = im.convert('L')
imgry.save('g' + name)
out = imgry.point(table, '1')
out.save('b' + name)
string = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
im = Image.open('b1.jpg')
enhancer = ImageEnhance.Contrast(im)
im = enhancer.enhance(6)
text = pytesseract.image_to_string(im, config=string)
text = text.strip('')
text = text.upper();
return text
def main():
guid = get_guid(t, search_config.second_header)
get_image(guid)
date = getverify1('1.jpg')
return guid,date
网友评论
代码块
```