1. 程式人生 > 其它 >Python selenium 自動化測試 --16--操作驗證碼

Python selenium 自動化測試 --16--操作驗證碼

技術標籤:python 測試自動化測試Selenium

使用pytesseract 和 Pillow操作驗證碼

(只能操作簡單的驗證碼)

  1. 首先需要匯入響應的模組
	pip install pytesseract
	pip install Pillow
  1. 進行驗證碼的分析
    在這裡插入圖片描述
    • 首先是第一種(本次只針對第一種驗證碼來做演示):
    # 匯入模組
    import pytesseract
    from selenium import webdriver
    import time
    from PIL import Image
    
    1. 擷取整個頁面
    2. 根據驗證碼的id 或者 class 等屬性找到 該驗證碼的位置(獲取到左上頂點和右下頂點的位置)
    3
    . 使用座標對該驗證碼進行摳圖(使用Pillow這個庫) 4. 對截取出來的驗證碼,使用pytesseract庫來進行轉換 driver = webdriver.Chrome() driver.get('http://127.0.0.1:8080/image_test') driver.maximize_window() # 獲取驗證碼圖片 t = time.time() img_name = str(t) + '.png' driver.save_screenshot("") # 擷取整個螢幕 yzm = driver.find_element_by_id("image_yzm"
    ) print(yzm.location) left = yzm.location['x'] top= yzm.location['y'] right = yzm.location['width'] + left height = yzm.location['height'] + top im = Image.open(img_name) # 進行摳圖 img = im.crop((left,top,right,height)) t = time.time() img_name2 = str(t) + '.png' img.save(img_name2) # 使用pytesseract 來進行識別
    image1 = Image.open(img_name2) str_image = pytesseract.image_to_string(image1) print(str_image)