1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| import tesserocr import os import time import re import tesserocr from selenium import webdriver from io import BytesIO from PIL import Image from retrying import retry import matplotlib.pyplot as plt import numpy as np import matplotlib.pyplot as plt from PIL import Image from selenium.webdriver.support.wait import WebDriverWait from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException,NoSuchElementException
def preprocess(image): array =image array = np.where(image > 100, 255, 0) image = Image.fromarray(array.astype('uint8')) return image
def login(browser): username = "user" psw = "psw" browser.get("http://xsc.sicau.edu.cn/Sys/UserLogin.aspx") input = browser.find_element(By.ID, value='UserName') input.send_keys(username) input = browser.find_element(By.NAME, value='UserPass') input.send_keys(psw) browser.set_window_size(1000, 800) browser.save_screenshot('1.png') image = Image.open('1.png') image = image.convert('RGB') image = np.array(image) image = image[480:503, 1030:1103, :] image = preprocess(image) image = image.convert('L') plt.imshow(image) plt.show() code = tesserocr.image_to_text(image) code = code.strip() print("验证码识别结果", code) if code.isdigit(): input = browser.find_element(By.ID, value='CheckCode') code = str(code) input.send_keys(code) input = browser.find_element(By.ID, value='CheckCode') input.send_keys(code) input = browser.find_element(By.ID, value='Btn_OK') input.click() wait=WebDriverWait(browser,1) try: input=wait.until(EC.alert_is_present()) dig_alert = browser.switch_to.alert if(dig_alert.text=="用户名或密码错误!"): print("用户名或密码错误") return -1 dig_alert.accept() print("验证码失败了") return 0 except: return 1 else: print("识别有错") return 0
if __name__ == "__main__": browser = webdriver.Edge() browser.start_client() for i in range(5): p=login(browser) if p==1: print("登录成功") break elif p==-1: break
|