思路:

  1. 使用Selenium库把带有验证码的页面截取下来
  2. 利用验证码的xpath截取该页面的验证码
  3. 对验证码图片进行降噪、二值化、灰度化处理后再使用pytesser识别
  4. 使用固定的账户密码对比验证码正确或错误的关键字判断识别率

1. 截取验证码

  1. def cutcode(url,brower,vcodeimgxpath): #裁剪验证码
  2.  
  3. picName = url.replace(url,"capture.png") #改为.png后缀保存图片
  4. brower.get(url)
  5. brower.maximize_window() #放大
  6. brower.save_screenshot(picName) #截取网页
  7.  
  8. imgelement = brower.find_element_by_xpath(vcodeimgxpath) # 通过xpath定位验证码
  9. location = imgelement.location # 获取验证码的x,y轴
  10. size = imgelement.size # 获取验证码的长宽
  11. rangle = (int(location['x']), \
  12. int(location['y']), \
  13. int(location['x'] + size['width']), \
  14. int(location['y'] + size['height'])) # 写成我们需要截取的位置坐标
  15. i = Image.open(os.getcwd()+r'\capture.png') # 打开截图
  16. verifycodeimage = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域
  17. verifycodeimage.save(os.getcwd()+r'\verifycodeimage.png')
  18. return brower

2.  对验证码图片进行降噪、二值化、灰度化处理并识别

  1. def initTable(threshold=140): #降噪,图片二值化
  2. table = []
  3. for i in range(256):
  4. if i < threshold:
  5. table.append(0)
  6. else:
  7. table.append(1)
  8.  
  9. return table
  10.  
  11. def recode():
  12. image=Image.open(os.getcwd()+r'\verifycodeimage.png')
  13. image = image.convert('L') #彩色图转换为灰度图
  14.  
  15. binaryImage = image.point(initTable(), '') #将灰度图二值化
  16.  
  17. time.sleep(1)
  18.  
  19. vcode=image_to_string(binaryImage) #使用image_to_string识别验证码
  20. vcode = vcode.strip()
  21. return vcode

3. 通过点击登录按钮返回的信息判断验证码是否识别正确

  1. def login(vcode,brower,usernamexpath,passwordxpath,vcodexpath,submitxpath,username,password):
  2.  
  3. brower.find_element_by_xpath(usernamexpath).send_keys(username)
  4.  
  5. brower.find_element_by_xpath(passwordxpath).send_keys(password)
  6.  
  7. # 对文本框输入验证码值
  8. brower.find_element_by_xpath(vcodexpath).send_keys(vcode)
  9.  
  10. time.sleep(1)
  11. # 点击登录,sleep防止没输入就点击了登录
  12. brower.find_element_by_xpath(submitxpath).click()
  13.  
  14. # 等待页面加载出来
  15. time.sleep(1)
  16.  
  17. result = brower.page_source #获取页面的html
  18. return result

4. 接收识别验证码需要的参数,循环识别验证码

  1. def main():
  2. file_path = raw_input("param.txt path:")
  3. username = raw_input("username(default 'admin'):")
  4. password = raw_input("password(default '123456'):")
  5. codeerror = raw_input("vcode error key word in html(default '验证码错误'):")
  6. passerror = raw_input("vcode pass key word in html(default '密码错误'):")
  7. frequency = raw_input("How many time(default '100'):")
  8. vcodelen = raw_input("How many characters(default '4'):")
  9. remod = raw_input("choose remod(default:en+num,1:num,2:en):")
  10.  
  11. starttime = datetime.datetime.now()
  12. txt = open(file_path) #txt中需要的参数:url usernamexpath passwordxpath vcode_input_xpath vcode_image_xpath submit_xpath
  13. lines = txt.readlines()
  14. url = lines[0].split("=",1)[1]
  15. usernamexpath = lines[1].split("=",1)[1]
  16. passwordxpath = lines[2].split("=",1)[1]
  17. vcodexpath = lines[3].split("=",1)[1]
  18. vcodeimgxpath = lines[4].split("=",1)[1]
  19. submitxpath = lines[5].split("=",1)[1]
  20.  
  21. brower = webdriver.PhantomJS(executable_path=r'D:\Python27\PY\phantomjs-2.1.1-windows\bin\phantomjs.exe') #打开phantomjs.exe
  22. if username == '':
  23. username = "admin"
  24. if password == '':
  25. password = ''
  26. if codeerror == '':
  27. codeerror = u"验证码错误" #验证码错误时的关键字
  28. else:
  29. codeerror = codeerror.decode(sys.stdin.encoding) #识别为Unicode自动转换
  30. if passerror == '':
  31. passerror = u"密码错误" #验证码正确时的关键字
  32. else:
  33. passerror = passerror.decode(sys.stdin.encoding) #识别为Unicode自动转换
  34. if vcodelen == '':
  35. vcodelen = 4
  36. else:
  37. vcodelen = int(vcodelen)
  38. if remod == '':
  39. remod = '^[0-9]+$'
  40. elif remod == '':
  41. remod = '^[A-Za-z]+$'
  42. else:
  43. remod = '^[A-Za-z0-9]+$'
  44.  
  45. counterror = 0
  46. countture = 0
  47. if frequency == '':
  48. frequency = 100
  49. else:
  50. frequency = int(frequency)
  51. a = 0
  52. while a < frequency:
  53. brower = cutcode(url,brower,vcodeimgxpath)
  54. vcode = recode()
  55. if len(vcode) != vcodelen: #识别到的验证码长度不为4直接重新循环
  56. continue
  57. if re.match(remod,vcode): #判断识别到的验证码是否只有字母加数字
  58. result = login(vcode,brower,usernamexpath,passwordxpath,vcodexpath,submitxpath,username,password)
  59. if codeerror in result:
  60. print "[-]验证码错误"+vcode
  61. counterror += 1
  62. elif passerror in result:
  63. print "[+]验证码正确"+vcode
  64. countture += 1
  65. else:
  66. continue
  67. else:
  68. continue
  69. a += 1
  70.  
  71. os.remove(os.getcwd()+r'\verifycodeimage.png')
  72. os.remove(os.getcwd()+r'\capture.png')
  73. brower.close() #关闭浏览器
  74.  
  75. #把数字转换为str再print
  76. rat = str('%.3f%%' % (countture/frequency*100))
  77. countture = bytes(countture)
  78. counterror = bytes(counterror)
  79. endtime = datetime.datetime.now()
  80. runtime = str((endtime-starttime).seconds/3600*60)
  81. print "[+]验证码正确次数:"+countture
  82. print "[-]验证码错误次数:"+counterror
  83. print "[+]识别率:"+rat
  84. print "运行时间:"+runtime+"min"
  85.  
  86. if __name__ == '__main__':
  87. main()

  这种方法识别验证码的效率比较低,但是因为写这个代码要识别的网站的验证码url打开时空白、空白的!然后想到这种方法虽然是效率比较低,但是适用性还是较广的,毕竟可以模拟人为操作浏览器。

  然后有个缺点就是识别全数字的验证码正确率奇低==因为处理完验证码图片后数字就会变得有缺失==

  如果说运行的过程中xpath的value出现问题了,有可能是网页还没加载出来就已经被截图了(xpath直接在网页上右键检查元素,然后再那个html代码里右键复制xpath就好了)

param.txt的demo(=与路径中间不要有空格!!):

  1. url =
  2. username_xpath =//*[@id="txtUserName"]
  3. password_xpath =//*[@id="txtPassword"]
  4. vcode_input_xpath =//*[@id="txtValCode"]
  5. vcode_image_xpath =//*[@id="imgVerify"]
  6. submit_xpath =//*[@id="Button1"]

一开始写这个打算识别的目标站,只有57识别率==然后效率很低==毕竟不用自己写算法识别什么的。代码的排布什么的也挺烂的,不要介意啦==:

Python Selenium、PIL、pytesser 识别验证码的更多相关文章

  1. Python+Selenium+PIL+Tesseract真正自动识别验证码进行一键登录

    Python 2.7 IDE Pycharm 5.0.3 Selenium:Selenium的介绍及使用,强烈推荐@ Eastmount的博客 PIL : Pillow-3.3.0-cp27-cp27 ...

  2. Python+selenium+pil+tesseract实现自动识别验证码

    一.环境搭建准备: 1.Python下载,安装以及环境配置 2.IDE pycharm 工具下载,安装 3.ie浏览器 4.selenium 5.pil:pil第三方库的下载,win下安装whl文件, ...

  3. Python之selenium+pytesseract 实现识别验证码自动化登录脚本

    今天写自己的爆破靶场WP时候,遇到有验证码的网站除了使用pkav的工具我们同样可以通过py强大的第三方库来实现识别验证码+后台登录爆破,这里做个笔记~~~ 0x01关于selenium seleniu ...

  4. python+selenium,实现带有验证码的自动化登录功能

    python+selenium的环境准备,请自行安装完成,这里直接贴代码,方便做项目时直接使用. import time from selenium import webdriver from PIL ...

  5. Selenium+Tesseract-OCR智能识别验证码爬取网页数据

    1.项目需求描述 通过订单号获取某系统内订单的详细数据,不需要账号密码的登录验证,但有图片验证码的动态识别,将获取到的数据存到数据库. 2.整体思路 1.通过Selenium技术,无窗口模式打开浏览器 ...

  6. python pytesseract——3步识别验证码的识别入门

    验证码识别是个大工程,但入门开始只要3步.需要用到的库PIL.pytesserac,没有的话pip安装.还有一个是tesseract-ocr 下载地址:https://sourceforge.net/ ...

  7. Python利用PIL生成随机验证码图片

    安装pillow: pip install pillow PIL中的Image等模块提供了创建图片,制作图片的功能,大致的步骤就是我们利用random生成6个随机字符串,然后利用PIL将字符串绘制城图 ...

  8. python 用 PIL 模块 画验证码

    PIL 简单绘画 def get_code_img(request): from PIL import Image, ImageDraw, ImageFont import random def ra ...

  9. python识别验证码——PIL,pytesser,pytesseract的安装

    1.使用Python识别验证码需要安装Python的图像处理模块(PIL.pytesser.pytesseract) (安装过程需要pip,在我的Python中已经安装pip了,pip的安装就不在赘述 ...

随机推荐

  1. Linux下设置Tomcat开机自启动

    --未验证 第一步:在/etc/init.d下新建一个文件tomcat(需要root操作权限) vi /etc/init.d/tomcat 然后点击"i"写下如下代码,tomcat ...

  2. Oracle查看表结构的方法【我】

    Oracle查看表结构的方法   方法一: 在命令窗口下输入   DESC table_name;  回车       方法二: 在sql窗口下   SELECT DBMS_METADATA.GET_ ...

  3. ifc构件加载到树形控件中

    void IfcTreeWidget::setParentCheckState(QTreeWidgetItem *item) { if(!item) return; ; int childCount ...

  4. Maven打包SpringBoot

    Pom文件提交plugin <build> <finalName>Site</finalName><!--文件名可自定义--> <plugins& ...

  5. CentOS7下搭建zabbix监控(五)——Web端配置自动发现并注册

    好像有点问题,没法自动添加主机,我后期再测测 (1).自动发现主机并注册 1)创建发现规则 2)编辑自动发现规则信息(这两步不配置问题也不大,因为在动作中也有主机IP地址) 3)添加自动发现的动作 4 ...

  6. 深入理解Java虚拟机 - 书评

    谈起<深入理解java虚拟机>这本书,让我印象深刻的就是换工作跳槽面试的时候,当时刚进入java开发这个行业的时候,平时只是做一些对数据库的增删改查等功能,当自己技术增长一些的时候,就开始 ...

  7. Python 爬虫从入门到进阶之路

    https://www.cnblogs.com/weijiutao/p/10735455.html

  8. NodeJs本地搭建服务器,模拟接口请求,获取json数据

    最近在学习Node.js,虽然就感觉学了点皮毛,感觉这个语言还不错,并且也会一步步慢慢的学着的,这里实现下NodeJs本地搭建服务器,模拟接口请求,获取json数据. 具体的使用我就不写了,这个博客写 ...

  9. php判断进程是否存在

    //计划任务定时检测master进程是否存在,不存在则启动,以root用户运行 public function checkMaster() { $cmd = 'ps axu|grep "Uc ...

  10. 01.轮播图之二 :tableView 轮播

    在做这个tablevew轮播的时候,重要的就是修改frame 和view 的翻转了:::: 也是不难的,概要的设计和scroll 轮播是一致的: 首先是 .h 的文件 @interface Table ...