python+selenium2自動化---使用pytesseract和Pillow實現驗證碼識別
阿新 • • 發佈:2020-08-09
這種方式只能對簡單的驗證碼起作用,複雜的就獲取不到了。
驗證碼識別思路:
1、獲取整個螢幕截圖
2、獲取驗證碼圖片的座標
3、摳圖獲取驗證碼圖片
4、使用pytesseract識別驗證碼
示例程式碼
import os
from time import sleep
import pytesseract
from selenium import webdriver
from PIL import Image
class TestCase():
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.get( 'http://es.bnuz.edu.cn/')
def test01(self):
#獲取螢幕截圖
self.driver.get_screenshot_as_file(os.path.dirname(__file__)+'/螢幕截圖.png')
#獲取驗證碼圖片元素
ele = self.driver.find_element_by_xpath('//*[@id="yzm_dd"]/img')
#獲取驗證碼圖片左上角的座標
location = ele.location
size = ele.size
print(location)
print(size)
#驗證碼圖片的大小
left = location['x']
top = location['y']
right = size['width'] + left
height = size['height'] + top
#如果是retina螢幕,需要這樣
dpr = self.driver.execute_script('return window.devicePixelRatio')
#摳圖獲取驗證碼圖片
im = Image.open(os.path.dirname(__file__)+'/螢幕截圖.png')
im_new = im.crop((left*dpr,top*dpr,right*dpr,height*dpr))
im_new.save(os.path.dirname(__file__)+'/驗證碼圖片.png')
sleep(3)
self.driver.quit()
def test02():
img = Image.open(os.path.dirname(__file__)+'/驗證碼圖片.png')
res = pytesseract.image_to_string(img)
print(res)
if __name__ == '__main__':
TestCase.test02()
獲取到的整個螢幕截圖:
驗證碼圖片:
輸出結果: