1. 程式人生 > 實用技巧 >登入頁面圖片驗證碼獲取(OCR)

登入頁面圖片驗證碼獲取(OCR)

百度OCR網站地址:https://ai.baidu.com,新建圖文識別產品,拿到對應的appid、appkey、secretkey

ocr提供了模板,可以直接複製

安裝三方庫

pip install baidu-aip

pip install pillow

from selenium import webdriver
import time
from PIL import Image
from aip import AipOcr
from os import path

class login():

    def get_code(self, browser):
        # (3)獲取圖片驗證碼座標
code_ele = browser.find_element_by_xpath("//img[@id='captcha']") print("驗證碼的座標為:", code_ele.location)#控制檯檢視{'x': 1086, 'y': 368} print("驗證碼的大小為:", code_ele.size)# 圖片大小{'height': 40, 'width': 110} # (4)圖片4個點的座標位置 left = code_ele.location['x']#x點的座標 top = code_ele.location['
y']#y點的座標 right = code_ele.size['width']+left#上面右邊點的座標 down = code_ele.size['height']+top#下面右邊點的座標 image = Image.open('D:/pic.png') # (4)將圖片驗證碼擷取 code_image = image.crop((left, top, right, down)) code_image.save('D:/pic1.png')#擷取的驗證碼圖片儲存為新的檔案 def baiduOCR(self, picfile, outfile): #
picfile:圖片檔名 outfile:輸出檔案 filename = path.basename(picfile) # 圖片名稱 # 百度提供 """ 你的 APPID AK SK """ APP_ID = '23054650' # 這是你產品服務的appid API_KEY = 'kEKxwQx9TEOWCKflaG4CXR2C' # 這是你產品服務的appkey SECRET_KEY = 'AxzVIi56TIn8zliGDekGc735029fUTlP' # 這是你產品服務的secretkey client = AipOcr(APP_ID, API_KEY, SECRET_KEY) i = open(picfile, 'rb') img = i.read() print("正在識別圖片:\t" + filename) """ 呼叫通用文字識別(高精度版) """ message = client.basicAccurate(img) print("識別成功!") i.close() # with open(outfile, 'a+') as fo: # 這邊是寫進.txt檔案 # fo.writelines("*" * 60 + '\n') # 搞點花裡胡哨的做區分 # fo.writelines("識別圖片:\t" + filename + "\n" * 2) # fo.writelines("文字內容:\n") # # 輸出文字內容 # for text in message.get('words_result'): # 識別的內容 # fo.writelines(text.get('words') + '\n') # fo.writelines('\n' * 2) # print("文字匯出成功!") print() # 將每行文字拼接成一個整體 string_text = "" for text in message.get('words_result'): string_text += text.get('words') print('string_text:', string_text) return string_text if __name__ == '__main__': l = login() base_url = 'http://xxxxxxxxx' browser = webdriver.Chrome() browser.maximize_window() # 最大化檢視 browser.implicitly_wait(10) browser.get(base_url) time.sleep(5) # (1)登入頁面截圖 browser.save_screenshot("D:/pic.png") # 可以修改儲存地址 # (2)基操 browser.find_element_by_name("username").send_keys("admin") browser.find_element_by_name("password").send_keys("123456") time.sleep(2) l.get_code(browser) outfile = 'D:/export1.txt' # 儲存的檔案 string_text = l.baiduOCR('D:/pic1.png', outfile) # print('圖片文字提取結束!文字輸出結果位於 %s 檔案中。' % outfile) browser.find_element_by_name("captcha").send_keys(string_text) browser.find_element_by_xpath('//*[@id="submit"]').click()