识别图片验证码自动登录demo
-
使用selenium需要下载chromedriver 网址: http://npm.taobao.org/mirrors/chromedriver/ 下载跟自己浏览器版本号最接近的版本.
-
https://cloud.baidu.com/ 百度开发平台. https://cloud.baidu.com/doc/OCR/s/zk3h7xz52 文字识别开发文档
-
导包
import random from selenium import webdriver import time import requests import json import base64 import urllib
-
建立浏览器对象和抓取验证码图片
# 建立浏览器对象 browser = webdriver.Chrome('D:\python\python6\chromedriver.exe') # 打开网址 browser.get('http://localhost:8080/register') # 等待5秒 time.sleep(3) # 选择元素 myimg = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[3]/td[2]/img') # 截取元素图 myimg.screenshot('register.png') # 随机生成用户名与密码 num = '0123456789qwertyuiopasdfghjklzxcvbnm' nums = '0123456789'
-
调用百度接口识别我们截图的验证码图片
def Disc_img(): # 请求调用百度接口 res = requests.get( 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=edowjGnGuO1lTIAvmpmNUcrc&client_secret=Ob8txKjSChTdp2FvEMkdCBIwFoL0GKTx').json() token = res['access_token'] # 识别图像 url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token # 构造头部 headr = {'Contene-Type': 'application/x-www-form-urlencoded'} # 构造图片 img = open('./register.png', 'rb') temp_img = img.read() # img.close() # 构建参数 data = {'image': base64.b64encode(temp_img)} # 编码 data = urllib.parse.urlencode(data) # 发送请求 res = requests.post(url=url, data=data, headers=headr).text respone = json.loads(res) # 获取识别完毕的验证码 code = respone['words_result'][0]['words'] return code
-
定位标签写入数据,把用户名和密码保存text
def send_set(): username = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[1]/td[2]/input') username.clear() # 设定随机字符串 user = '' # 随机生成用户名 for i in range(6): num_index = random.randrange(len(num)) num_s = num[num_index] user += num_s f = open('user.txt', 'a', encoding='utf-8') f.write('用户名:' + user) # 写入用户名 username.send_keys(user) # 等待三秒 time.sleep(2) # 定位密码框 password = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[2]/td[2]/input') password.clear() pwd = '' for i in range(6): num_index = random.randrange(len(num)) num_s = num[num_index] pwd += num_s f = open('user.txt', 'a', encoding='utf-8') f.write('密码:' + pwd) password.send_keys(pwd) time.sleep(2) # 定位验证码输入框 codem = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[4]/td[2]/input') codem.clear() codem.send_keys(Disc_img()) # 定位手机号 phone = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[5]/td[2]/input') phone.clear() # 随机手机号第二位 start_two = str(random.choice([3, 4, 5, 7, 8])) end = '' for i in range(9): nums_index = random.randrange(len(nums)) nums_s = nums[nums_index] end += nums_s phone.send_keys('1'+start_two+end) # 定位提交按钮 but = browser.find_element_by_xpath('//*[@id="app"]/div/section/div[2]/table/tr[6]/td[2]/button') but.click() time.sleep(3) return if __name__ == '__main__': send_set()
-
最终效果