python+selenium识别验证码并登录的示例代码

yipeiwu_com5年前Python基础

由于工作需要,登录网站需要用到验证码。最初是研究过验证码识别的,但是总是不能获取到我需要的那个验证码。直到这周五,才想起这事来,昨天顺利的解决了。

下面正题:

python版本:3.4.3

所需要的代码库:PIL,selenium,tesseract

先上代码:

#coding:utf-8
import subprocess
from PIL import Image
from PIL import ImageOps
from selenium import webdriver
import time,os,sys
def cleanImage(imagePath):
  image = Image.open(imagePath)  #打开图片
  image = image.point(lambda x: 0 if x<143 else 255) #处理图片上的每个像素点,使图片上每个点“非黑即白”
  borderImage = ImageOps.expand(image,border=20,fill='white')
  borderImage.save(imagePath)

def getAuthCode(driver, url="http://localhost/"):
  captchaUrl = url + "common/random"
  driver.get(captchaUrl) 
  time.sleep(0.5)
  driver.save_screenshot("captcha.jpg")  #截屏,并保存图片
  #urlretrieve(captchaUrl, "captcha.jpg")
  time.sleep(0.5)
  cleanImage("captcha.jpg")
  p = subprocess.Popen(["tesseract", "captcha.jpg", "captcha"], stdout=\
             subprocess.PIPE,stderr=subprocess.PIPE)
  p.wait()
  f = open("captcha.txt", "r")
  
  #Clean any whitespace characters
  captchaResponse = f.read().replace(" ", "").replace("\n", "")
  print("Captcha solution attempt: " + captchaResponse)
  if len(captchaResponse) == 4:
    return captchaResponse
  else:
    return False

def withoutCookieLogin(url="http://org.cfu666.com/"):
  driver = webdriver.Chrome()
  driver.maximize_window()
  driver.get(url)
  while True:   
    authCode = getAuthCode(driver, url)
    if authCode:
      driver.back()
      driver.find_element_by_xpath("//input[@id='orgCode' and @name='orgCode']").clear()
      driver.find_element_by_xpath("//input[@id='orgCode' and @name='orgCode']").send_keys("orgCode")
      driver.find_element_by_xpath("//input[@id='account' and @name='username']").clear()
      driver.find_element_by_xpath("//input[@id='account' and @name='username']").send_keys("username")
      driver.find_element_by_xpath("//input[@type='password' and @name='password']").clear()
      driver.find_element_by_xpath("//input[@type='password' and @name='password']").send_keys("password")       
      driver.find_element_by_xpath("//input[@type='text' and @name='authCode']").send_keys(authCode)
      driver.find_element_by_xpath("//button[@type='submit']").click()
      try:
        time.sleep(3)
        driver.find_element_by_xpath("//*[@id='side-menu']/li[2]/ul/li/a").click()
        return driver
      except:
        print("authCode Error:", authCode)
        driver.refresh()
  return driver
driver = withoutCookieLogin("http://localhost/")
driver.get("http://localhost/enterprise/add/")

怎么获取我们需要的验证码

在这获取验证码的道路上,我掉了太多的坑,看过太多的文章,很多都是教你验证码的识别方法,但是没有说明,怎么获取你当前需要的验证码图片。

我的处理方法是:

1.先用selenium打开你需要的登录的页面地址url1

2.通过审核元素获取验证码的地址url2(其实最简单的是右键打开新页面)

3:在url1页面,输入地址url2进入url2页面,然后截屏保存验证码页面

4:处理验证码得到验证码字符串。然后点击浏览器后退按钮,返回url1登录页面

5:输入登录需要的信息和验证码

6:点击登录

7:验证登录后的页面,判断是否成功,若不成功则需要重新1-7的操作。

为了保护公司的信息,这个页面是我本地搭的服务,我在伯乐在线注册页面进行测试过这个验证码获得方法,可以通过。(这个验证码的处理方法,仅限验证码背景是像素点,若验证码有横线需额外处理。)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用python进行波形及频谱绘制的方法

如下所示: # -*- coding: UTF-8 -*- import wave import numpy as np import matplotlib.pyplot as pl...

使用python和pygame制作挡板弹球游戏

使用python和pygame制作挡板弹球游戏

python是个很有趣的语言,可以在cmd命令窗口运行,还有很多的功能强大的模块。 学了一天pygame,用python和pygame写一个简单的挡板弹球游戏。 2018年6月21日 0...

python字典DICT类型合并详解

python字典DICT类型合并详解

本文为大家分享了python字典DICT类型合并的方法,供大家参考,具体内容如下 我要的字典的键值有些是数据库中表的字段名, 但是有些却不是, 我需要把它们整合到一起, 因此有些这篇文章...

Python处理时间日期坐标轴过程详解

Python处理时间日期坐标轴过程详解

1. 前言 当日期数据作为图表的坐标轴时通常需要特殊处理,应为日期字符串比较长,容易产生重叠现象 2. 设定主/次刻度 2.1 引用库 from matplotlib.date...

Python实现的金山快盘的签到程序

复制代码 代码如下:__author__ = 'clownfish'#coding:utf-8import urllib2,urllib,cookielib,json username...