验证码识别(完整版)

因为最近要考试=。=没时间写就贴个代码

=================test.py==============================

import time
import pyautogui
# screenWidth, screenHeight = pyautogui.size()
# currentMouseX, currentMouseY = pyautogui.position()
# pyautogui.moveTo(100, 150)
# pyautogui.click()
# #  鼠标向下移动10像素
# pyautogui.moveRel(None, 10)
# pyautogui.doubleClick()
# #  用缓动/渐变函数让鼠标2秒后移动到(500,500)位置
# #  use tweening/easing function to move mouse over 2 seconds.
# pyautogui.moveTo(1800, 500, duration=2, tween=pyautogui.easeInOutQuad)
# #  在每次输入之间暂停0.25秒
# pyautogui.typewrite('Hello world!', interval=0.25)
# pyautogui.press('esc')
# pyautogui.keyDown('shift')
# pyautogui.press(['left', 'left', 'left', 'left', 'left', 'left'])
# pyautogui.keyUp('shift')
# pyautogui.hotkey('ctrl', 'c')
# try:
#     while True:
#         time.sleep(1)
#         x, y = pyautogui.position()
#         print(x,y)
# except KeyboardInterrupt:
#     print('\nExit.')
# pyautogui.keyDown('alt')
# # pyautogui.press('tab')
# pyautogui.keyUp('alt')
def move():
        pyautogui.moveTo(939,502)
        pyautogui.click()
        pyautogui.keyDown('ctrl')
        for i in range(11):
            pyautogui.scroll(100)
        pyautogui.keyUp('ctrl')
def movept():
    pyautogui.moveTo(115, 1002)
    pyautogui.click()

def scshot():
    im=pyautogui.screenshot('1.jpg',region=(230,972,114,50))


def print(str):
    pyautogui.typewrite(str,0.25)

def delete():
    pyautogui.moveTo(184,975)
    pyautogui.click()
    pyautogui.press(['backspace','backspace','backspace','backspace','backspace','backspace'])
    pyautogui.moveTo(939,502)
    pyautogui.click()

def end():
    pyautogui.hotkey('ctrl','0')

============================yanzhengma.py=======================

#coding:utf-8
import cv2
from  PIL import Image
import subprocess
import requests
from bs4 import BeautifulSoup
import re
import os
import time
from selenium import webdriver
from urllib.request import urlopen
import test
def image_area(area):
    img_1=Image.open(area)
    img=cv2.imread(area)
    # cv2.namedWindow("image")
    # cv2.imshow("image",img)
    # cv2.waitKey(1)
    # cv2.destroyWindow("image")
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    _, inv=cv2.threshold(gray,180,255,cv2.THRESH_BINARY_INV)
    for i in range(len(inv)):
        for j in range(len(inv[i])):
            if inv[i][j]==255:
                count=0
                for k in range(-2,3):
                    for l in range(-2,3):
                        try:
                            if inv[i+k][j+l]==255:
                                count+=1
                        except IndexError:
                            pass
                if count <=8:
                    inv[i][j]=0
    dilation=cv2.dilate(inv,(8,8),iterations=1)
    cv2.imwrite('C:\\Users\\assu\\Pictures\\test.jpg', dilation)
    # cmd='tesseract C:\\Users\\assu\\Pictures\\test.jpg C:\\Users\\assu\\Pictures\\result'
    # cmd=cmd.encode(locale.getdefaultlocale()[1])
    f=open('C:\\Users\\assu\\Pictures\\result.txt','w')
    image='C:\\Users\\assu\\Pictures\\test.jpg'
    child = subprocess.Popen('tesseract C:\\Users\\assu\\Pictures\\test.jpg C:\\Users\\assu\\Pictures\\result',
                             shell=True, cwd='C:\\Users\\assu')
    child.wait()
    # os.system(cmd)
    text = open('C:\\Users\\assu\\Pictures\\result.txt',encoding='utf-8').read().strip()
    # #os.remove(image)
    # print("验证码为" + text)
    return text

def Pt(x):
    head="C:\\Users\\assu\\Pictures\\"
    head_2="C:\\Users\\assu\\PycharmProjects\\yanzhengma\\yanzheng\\"
    test.move()
    for i in range(1,x):
        test.movept()
        time.sleep(0.5)
        test.scshot()
        area=head_2+"1.jpg"
        text=image_area(area)
        test.print(text)
        test.delete()
    test.end()

def getimage():
    url='http://z2.micinv.com/SignIn.aspx'
    head='http://z2.micinv.com/'
    html=requests.get(url)
    bs=BeautifulSoup(html.text,'lxml')
    vaild=bs.select("#validatecode")
    weiba=vaild[0].get("src")
    url_1=head+weiba
    return url_1

def download_image(url,i=1):
    filename=url.split('/')[-1]
    ext=filename.split('.')[-1]
    filename='{}'.format(i)+'.jpg'
    url_save = 'C:\\Users\\assu\\Pictures\\'
    try:
        image=urlopen(url)
        f=open(os.path.join(url_save,filename),'wb')
        f.write(image.read())
        f.close()
    except:
        print("{}无法读取".format(filename))
    print(filename)

def deleteimage():
    for i in range(600):
        image='C:\\Users\\assu\\Pictures\\{}.jpg'.format(i)
        try:
            os.remove(image)
        except:
            print("不存在")
#area=getimage()
#print(area)
#for i in range(1000):
#    download_image(area,i)
Pt(10)

跟我电脑的屏幕大小适配不知道别的行不行

功能实现视频嘻嘻

杭电选课自动登录

#coding:utf-8
import cv2
from PIL import Image
import subprocess
import requests
from bs4 import BeautifulSoup
import re
import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from urllib.request import urlopen
# import yanzheng.yanzhengma
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url_agree=’http://jxgl.hdu.edu.cn/xs_main.aspx?xh=16184117′
url=”http://jxgl.hdu.edu.cn/”
chromedriver=’C:\\Users\\assu\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe’
os.environ[“webdriver.chrome.driver”]=chromedriver
driver=webdriver.Chrome(chromedriver)
driver.get(url)
driver.find_element_by_id(‘username’).send_keys(‘********’)#自己的学号
pwd=driver.find_element_by_id(‘password’)
print(pwd.text)
pwd.send_keys(‘********’)#自己密码
pwd.send_keys(Keys.RETURN)
time.sleep(2)
print(driver.get_window_position())
driver.maximize_window()
print(driver.get_window_position())
driver.find_element_by_link_text(‘网上选课’).click()
driver.find_element_by_link_text(‘选体育课’).click()
# tag=driver.find_element_by_tag_name(“ListBox1”)
# print(tag.text)
# time.sleep(1)
# # driver.find_element_by_link_text(‘体育-网球(男)‖1.0‖汤更国‖‖周五第3,4节{第1-16周}‖西边网球场‖35‖‖,公办本科2017级男生,公办本科2016级男生,‖下沙’).click()
# # driver.find_element_by_id(‘RadioButtonList1_0’).click()
# driver.find_element_by_tag_name(“ListBox1”)
id=driver.find_element_by_id(‘RadioButtonList1’)
print(id.text)

验证码识别

#coding:utf-8
import cv2
from  PIL import Image
import subprocess
import requests
from bs4 import BeautifulSoup
import re
import os
from selenium import webdriver
from urllib.request import urlopen
def image_area(area):
    img_1=Image.open(area)
    img=cv2.imread(area)
    cv2.namedWindow("image")
    cv2.imshow("image",img)
    cv2.waitKey(0)
    cv2.destroyWindow("image")
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    _, inv=cv2.threshold(gray,180,255,cv2.THRESH_BINARY_INV)
    for i in range(len(inv)):
        for j in range(len(inv[i])):
            if inv[i][j]==255:
                count=0
                for k in range(-2,3):
                    for l in range(-2,3):
                        try:
                            if inv[i+k][j+l]==255:
                                count+=1
                        except IndexError:
                            pass
                if count <=12:
                    inv[i][j]=0
    dilation=cv2.dilate(inv,(10,10),iterations=1)
    cv2.imwrite('C:\\Users\\assu\\Pictures\\test.jpg', dilation)
    # cmd='tesseract C:\\Users\\assu\\Pictures\\test.jpg C:\\Users\\assu\\Pictures\\result'
    # cmd=cmd.encode(locale.getdefaultlocale()[1])
    f=open('C:\\Users\\assu\\Pictures\\result.txt','w')
    image='C:\\Users\\assu\\Pictures\\test.jpg'
    child = subprocess.Popen('tesseract C:\\Users\\assu\\Pictures\\test.jpg C:\\Users\\assu\\Pictures\\result',
                             shell=True, cwd='C:\\Users\\assu')
    child.wait()
    # os.system(cmd)
    text = open('C:\\Users\\assu\\Pictures\\result.txt',encoding='utf-8').read(4).strip()
    #os.remove(image)
    print("验证码为" + text)

def Pt(x):
    for i in range(1,x):
        area="C:\\Users\\assu\\Pictures\\"+"{0}".format(i)+".jpg"
        image_area(area)

def getimage():
    url='http://z2.micinv.com/SignIn.aspx'
    head='http://z2.micinv.com/'
    html=requests.get(url)
    bs=BeautifulSoup(html.text,'lxml')
    vaild=bs.select("#validatecode")
    weiba=vaild[0].get("src")
    url_1=head+weiba
    return url_1

def download_image(url,i=1):
    filename=url.split('/')[-1]
    ext=filename.split('.')[-1]
    filename='{}'.format(i)+'.jpg'
    url_save = 'C:\\Users\\assu\\Pictures\\'
    try:
        image=urlopen(url)
        f=open(os.path.join(url_save,filename),'wb')
        f.write(image.read())
        f.close()
    except:
        print("{}无法读取".format(filename))
    print(filename)

#area=getimage()
#print(area)
#for i in range(1000):
#    download_image(area,i)
Pt(2)

Qlearning算法

import numpy as np
import random
# 建立 Q 表
q = np.zeros((6, 6))
q = np.matrix(q)
# 建立 R 表
r = np.array([[-1, -1, -1, -1, 0, -1],
              [-1, -1, -1, 0, -1, 100],
              [-1, -1, -1, 0, -1, -1],
              [-1, 0, 0, -1, 0, -1],
              [0, -1, -1, 0, -1, 100],
              [-1, 0, -1, -1, 0, 100]])
r = np.matrix(r)
# 贪婪指数
gamma = 0.8
for i in range(100):
    # 对每一个训练,随机选择一种状态
    state = random.randint(0, 5)
    while state != 5:
        # 选择r表中非负的值的动作
        r_pos_action = []
        for action in range(6):
            if r[state, action] >= 0:
                r_pos_action.append(action)
        next_state = r_pos_action[random.randint(0, len(r_pos_action) - 1)]
        q[state, next_state] = r[state, next_state] + gamma * q[next_state].max()
        state = next_state
print(q)
print(r_pos_action)
# 验证

for i in range(10):
    print("第{}次验证".format(i + 1))

    state = random.randint(0, 5)
    print('机器人处于{}'.format(state))
    count = 0
    while state != 5:
        if count > 20:
            print('fail')
            break
        # 选择最大的q_max
        q_max = q[state].max()

        q_max_action = []
        for action in range(6):
            if q[state, action] == q_max:
                q_max_action.append(action)

        next_state = q_max_action[random.randint(0, len(q_max_action) - 1)]
        print("the robot goes to " + str(next_state) + '.')
        state = next_state
        count += 1