侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python实现破解12306图片验证码的方法分析

Python  /  管理员 发布于 7年前   238

本文实例讲述了Python实现破解12306图片验证码的方法。分享给大家供大家参考,具体如下:

不知从何时起,12306的登录验证码竟然变成了按字找图,可以说是又提高了一个等次,竟然把图像识别都用上了。不过有些图片,不得不说有些变态,图片的清晰图就更别说了,明显是从网络上的图库中搬过来的。

谁知没多久,网络就惊现破解12306图片验证码的Python代码了,作为一个爱玩爱刺激的网虫,当然要分享一份过来。

代码大致流程:

1、将验证码图片下载下来,然后切图;
2、利用百度识图进行图片分析;
3、再利用正则表达式来取出百度识图的关键字,最后输出。

代码:

#!/usr/bin/python# # FileName  : fuck12306.py# # Author   : MaoMao Wang <[email protected]># # Created   : Mon Mar 16 22:08:41 2015 by ShuYu Wang# # Copyright  : Feather (c) 2015# # Description : fuck fuck 12306# # Time-stamp: <2015-03-17 10:57:44 andelf>from PIL import Imagefrom PIL import ImageFilterimport urllibimport urllib2import reimport json# hack CERTIFICATE_VERIFY_FAILED# https://github.com/mtschirs/quizduellapi/issues/2import sslif hasattr(ssl, '_create_unverified_context'):  ssl._create_default_https_context = ssl._create_unverified_contextUA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36"pic_url = "https://kyfw.12306.cn/otn/passcodeNew/getPassCodeNew?module=login&rand=sjrand&0.21191171556711197"def get_img():  resp = urllib.urlopen(pic_url)  raw = resp.read()  with open("./tmp.jpg", 'wb') as fp:    fp.write(raw)  return Image.open("./tmp.jpg")def get_sub_img(im, x, y):  assert 0 <= x <= 3  assert 0 <= y <= 2  WITH = HEIGHT = 68  left = 5 + (67 + 5) * x  top = 41 + (67 + 5) * y  right = left + 67  bottom = top + 67  return im.crop((left, top, right, bottom))def baidu_stu_lookup(im):  url = "http://stu.baidu.com/n/image?fr=html5&needRawImageUrl=true&id=WU_FILE_0&name=233.png&type=image%2Fpng&lastModifiedDate=Mon+Mar+16+2015+20%3A49%3A11+GMT%2B0800+(CST)&size="  im.save("./query_temp_img.png")  raw = open("./query_temp_img.png", 'rb').read()  url = url + str(len(raw))  req = urllib2.Request(url, raw, {'Content-Type':'image/png', 'User-Agent':UA})  resp = urllib2.urlopen(req)  resp_url = resp.read()   # return a pure url  url = "http://stu.baidu.com/n/searchpc?queryImageUrl=" + urllib.quote(resp_url)  req = urllib2.Request(url, headers={'User-Agent':UA})  resp = urllib2.urlopen(req)  html = resp.read()  return baidu_stu_html_extract(html)def baidu_stu_html_extract(html):  #pattern = re.compile(r'<script type="text/javascript">(.*?)</script>', re.DOTALL | re.MULTILINE)  pattern = re.compile(r"keywords:'(.*?)'")  matches = pattern.findall(html)  if not matches:    return '[UNKNOWN]'  json_str = matches[0]  json_str = json_str.replace('\\x22', '"').replace('\\\\', '\\')  #print json_str  result = [item['keyword'] for item in json.loads(json_str)]  return '|'.join(result) if result else '[UNKNOWN]'def ocr_question_extract(im):  # [email protected]:madmaze/pytesseract.git  global pytesseract  try:    import pytesseract  except:    print "[ERROR] pytesseract not installed"    return  im = im.crop((127, 3, 260, 22))  im = pre_ocr_processing(im)  # im.show()  return pytesseract.image_to_string(im, lang='chi_sim').strip()def pre_ocr_processing(im):  im = im.convert("RGB")  width, height = im.size  white = im.filter(ImageFilter.BLUR).filter(ImageFilter.MaxFilter(23))  grey = im.convert('L')  impix = im.load()  whitepix = white.load()  greypix = grey.load()  for y in range(height):    for x in range(width):      greypix[x,y] = min(255, max(255 + impix[x,y][0] - whitepix[x,y][0],        255 + impix[x,y][1] - whitepix[x,y][1],        255 + impix[x,y][2] - whitepix[x,y][2]))  new_im = grey.copy()  binarize(new_im, 150)  return new_imdef binarize(im, thresh=120):  assert 0 < thresh < 255  assert im.mode == 'L'  w, h = im.size  for y in xrange(0, h):    for x in xrange(0, w):      if im.getpixel((x,y)) < thresh:        im.putpixel((x,y), 0)      else:        im.putpixel((x,y), 255)if __name__ == '__main__':  im = get_img()  #im = Image.open("./tmp.jpg")  print 'OCR Question:', ocr_question_extract(im)  for y in range(2):    for x in range(4):      im2 = get_sub_img(im, x, y)      result = baidu_stu_lookup(im2)      print (y,x), result

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools..net.cn/regex/javascript

正则表达式在线生成工具:
http://tools..net.cn/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。


  • 上一条:
    Python2.7+pytesser实现简单验证码的识别方法
    下一条:
    解决python使用open打开文件中文乱码的问题
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客