1.需要導入以下包(pytesseract.src里面應該要用notepad++編輯Tesseract-OCR路徑,如我的第26行: tesseract_cmd = 'C:\Program Files (x86)\Tesseract-OCR\\tesseract')
from PILimport Image
from pytesseract.srcimport pytesseract
2.代碼實現(xiàn)如下:
?# 截取當前網頁,該網頁有我們需要的驗證碼
driver.save_screenshot('D://aa.png')
# 定位驗證碼
imgelement = driver.find_element_by_xpath(self.IMAGE_CODE_PATH)
# 獲取驗證碼x,y軸坐標
location = imgelement.location
# 獲取驗證碼的長寬
size = imgelement.size
# 寫成我們需要截取的位置坐標
rangle = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
# 打開截圖
i = Image.open("D://aa.png")
# 使用Image的crop函數(shù),從截圖中再次截取我們需要的區(qū)域
frame4 = i.crop(rangle)
frame4.save('D://frame4.png')
img = Image.open('D://frame4.png')
# 銳化圖片,這里很關鍵
im = img.point(lambda i: i *2.5)
BB = pytesseract.image_to_string(im)
print(u"識別的驗證碼為:" + BB)
3.用try……except Exception取識別出來的0,2,4,6位,為防止錯誤,如識別不對,重新執(zhí)行識別圖形碼方法。
try:
????for iin range(0, 7, 2):
????driver.find_element_by_xpath(self.VERIF_CODE).send_keys(BB[i])
????sleep(3)
????driver.find_element_by_xpath(self.SUMIT).click()
????sleep(3)
except Exception:
????driver.close()
????self.get_streen(user_name,pwd)