Python實(shí)現(xiàn)破解12306圖片驗(yàn)證碼的方法分析
本文實(shí)例講述了Python實(shí)現(xiàn)破解12306圖片驗(yàn)證碼的方法。分享給大家供大家參考,具體如下:
不知從何時(shí)起,12306的登錄驗(yàn)證碼竟然變成了按字找圖,可以說(shuō)是又提高了一個(gè)等次,竟然把圖像識(shí)別都用上了。不過(guò)有些圖片,不得不說(shuō)有些變態(tài),圖片的清晰圖就更別說(shuō)了,明顯是從網(wǎng)絡(luò)上的圖庫(kù)中搬過(guò)來(lái)的。
誰(shuí)知沒多久,網(wǎng)絡(luò)就驚現(xiàn)破解12306圖片驗(yàn)證碼的Python代碼了,作為一個(gè)愛玩愛刺激的網(wǎng)蟲,當(dāng)然要分享一份過(guò)來(lái)。
代碼大致流程:
1、將驗(yàn)證碼圖片下載下來(lái),然后切圖;
2、利用百度識(shí)圖進(jìn)行圖片分析;
3、再利用正則表達(dá)式來(lái)取出百度識(shí)圖的關(guān)鍵字,最后輸出。
代碼:
#!/usr/bin/python # # FileName : fuck12306.py # # Author : MaoMao Wang <andelf@gmail.com> # # 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 Image from PIL import ImageFilter import urllib import urllib2 import re import json # hack CERTIFICATE_VERIFY_FAILED # https://github.com/mtschirs/quizduellapi/issues/2 import ssl if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context UA = "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): # git@github.com: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_im def 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款非常方便的正則表達(dá)式工具供大家參考使用:
JavaScript正則表達(dá)式在線測(cè)試工具:
http://tools.jb51.net/regex/javascript
正則表達(dá)式在線生成工具:
http://tools.jb51.net/regex/create_reg
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python正則表達(dá)式用法總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
使用 Django 進(jìn)行測(cè)試驅(qū)動(dòng)開發(fā)
本文分享了什么是測(cè)試驅(qū)動(dòng)開發(fā),并用測(cè)試驅(qū)動(dòng)開發(fā)的方式 創(chuàng)建了一個(gè)簡(jiǎn)單的 Django 應(yīng)用程序,感興趣的可以了解一下2021-11-11Python基于ThreadingTCPServer創(chuàng)建多線程代理的方法示例
這篇文章主要介紹了Python基于ThreadingTCPServer創(chuàng)建多線程代理的方法,結(jié)合實(shí)例形式分析了Python使用ThreadingTCPServer模塊實(shí)現(xiàn)多線程代理功能進(jìn)行網(wǎng)絡(luò)請(qǐng)求響應(yīng)的相關(guān)操作技巧,需要的朋友可以參考下2018-01-01python基于event實(shí)現(xiàn)線程間通信控制
這篇文章主要介紹了python基于event實(shí)現(xiàn)線程間通信控制,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-01-01python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符)
今天小編就為大家分享一篇python 輸出列表元素實(shí)例(以空格/逗號(hào)為分隔符),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12詳解windows python3.7安裝numpy問(wèn)題的解決方法
這篇文章主要介紹了windows python3.7安裝numpy問(wèn)題的解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08jupyter閃退怎么辦?jupyter閃退問(wèn)題的解決
這篇文章主要介紹了jupyter閃退怎么辦?jupyter閃退問(wèn)題的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01