python3定位并識別圖片驗證碼實現(xiàn)自動登錄功能
會用到的庫的
1、selenium的webdriver
2、tesserocr或者pytesseract進(jìn)行圖像識別
3、pillow的Image進(jìn)行圖片處理
from selenium import webdriver import tesserocr from PIL import Image
獲取驗證碼圖片方法1:
def get_code_image(file_name):
driver.save_screenshot(file_name) # 截取整個屏幕并保存
code_element = driver.find_element_by_class_name("verify_code_img___1Mei_") # 定位到驗證碼元素
left = code_element.location['x'] # 定位到截圖位置
top = code_element.location['y']
right = code_element.size['width'] + left
bottom = code_element.size['height'] + top
im = Image.open(file_name) # 從文件讀取截圖,截取驗證碼位置再次保存
img = im.crop((left, top, right, bottom))
img.save(file_name)
return file_name
獲取驗證碼圖片方法2:
def get_code_image(file_name):
code_element = driver.find_element_by_class_name("verify_code_img___1Mei_") # 定位到驗證碼元素
code_element.screenshot(file_name)
注:此方法截圖時屏幕會閃動,可能引發(fā)bug,如下圖,目前沒有解決

處理驗證碼圖片
def deal_code_image(file_name):
image = Image.open(file_name)
# image.show() #查看處理前的圖片
# 處理圖片去除干擾
# 將圖片轉(zhuǎn)化為灰度圖像
image = image.convert('L')
threshold = 90 # 設(shè)置臨界值,臨界值可調(diào)試
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
# image.show() #查看處理后的圖片
# 1:使用tesseract庫識別圖片中的驗證碼
# res = tesserocr.image_to_text(image)
# 2:使用pytesseract庫識別圖片中的驗證碼
res = pytesseract.image_to_string(image)
# print(res) #查看識別出來的文案
res = res.replace(" ", "") #去除結(jié)果中的空格
return res
處理前的圖片,有干擾,無法識別

處理后的圖片,基本可以識別

識別結(jié)果不一定準(zhǔn)確,如果驗證碼輸入錯誤,可以點(diǎn)擊換一張圖片再次識別,多次嘗試,本次不做說明
到此這篇關(guān)于python3定位并識別圖片驗證碼實現(xiàn)自動登錄的文章就介紹到這了,更多相關(guān)python識別圖片驗證碼實現(xiàn)自動登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)獲取當(dāng)前目錄下文件名代碼詳解
這篇文章主要介紹了Python實現(xiàn)獲取當(dāng)前目錄下文件名,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
在python中l(wèi)ist作函數(shù)形參,防止被實參修改的實現(xiàn)方法
這篇文章主要介紹了在python中l(wèi)ist作函數(shù)形參,防止被實參修改的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

