思路:
1、根據xpath獲取登錄頁面驗證碼元素區域的位置坐標
2、根據位置坐標截取驗證碼圖片
3、識別驗證碼文本,再使用UI或者接口登錄
步驟:
1、安裝tesseract,及pytesseract
參考:https://blog.csdn.net/qq_38900441/article/details/82823312
2、編寫裁剪、識別驗證碼、登錄腳本---station_web_login.py
# coding:utf-8 from PIL import Image from selenium import webdriver import pytesseract import time def cut_image(): # 截圖當前頁面 driver.save_screenshot('station_web_login.png') # 定位到該元素,獲取位置信息 img = driver.find_element_by_xpath('//img[@id="vildateImg"]') location = img.location size = img.size left = location['x'] top = location['y'] right = left + size['width'] bottom = top + size['height'] # 裁剪圖片 img = Image.open('station_web_login.png') cropped = img.crop((left, top, right, bottom)) cropped.save('station_web_login_checkCode.png') # 識別圖片 text = pytesseract.image_to_string(Image.open('station_web_login_checkCode.png').resize((300, 100))) # 模擬登錄 driver.find_element_by_xpath('//input[@id="username"]').send_keys('****') driver.find_element_by_xpath('//input[@id="password"]').send_keys('*******') driver.find_element_by_xpath('//input[@id="rand"]').send_keys(text) driver.find_element_by_xpath('//button[@id="submitlogin"]').click() # return text # 獲取頁面源碼 global source source = driver.page_source def login(): """ 登錄並獲取TOKEN和JSESSIONID :return: """ global driver driver = webdriver.Chrome() url = 'http://*******/login' driver.maximize_window() driver.get(url) # 等待兩秒截圖更清晰 time.sleep(2) # 裁剪圖片 cut_image() if '驗證碼不能為空或錯誤!' in source: driver.refresh() cut_image() if '歡迎使用' in source: # 獲取cookies,用於后續接口訪問鑒權 all_cookies = driver.get_cookies() TOKEN = all_cookies[0]['value'] JSESSIONID = all_cookies[1]['value'] driver.quit() return TOKEN, JSESSIONID
3、將station_web_login.py文件放置到框架中
然后在需要的地方引入
就可以使用里面的方法了,主要是login()方法
有用的博客:
https://www.sohu.com/a/235364612_729271--綜合實現
https://blog.csdn.net/hfutdog/article/details/82351549 --圖片裁剪