1. 程式人生 > 其它 >selenium - 圖形驗證碼

selenium - 圖形驗證碼

前言:用selenium做UI自動化,遇網站登入需要驗證碼!?WC...看了很多文章,最終解決不了我的需求,故做一下記錄分享我的解決方法

 

1.主要思路:

①.通過元素定位驗證碼圖片位置

②.使用screenshot方法將驗證碼截圖

③.將圖片亮度對比度調高提高識別精準度

④.使用ddddoc第三方庫識別驗證碼

 

2.元素定位

複製xpath定位驗證碼圖片並截圖命名img.png

img=driver.find_element_by_xpath('//*[@id="login-form"]/div[4]/span')
img.screenshot('E:\\captcha\\img.png')

 

 

3.提高亮度或對比度去除干擾因素

python中PIL模組中有一個叫做ImageEnhance的類,該類專門用於影象的增強處理,可以實現影象的亮度、對比度、色度和銳度四種方式的增強(或減弱)處理。

# -*- coding: UTF-8 -*-
import os
from PIL import Image
from PIL import ImageEnhance

# 原始影象
class ImageAugument(object):
    def __init__(self,img_name):
        self.image = Image.open('E:\\captcha\\
'+img_name) # image.show() # 亮度增強 def Brightness_img(self): enh_bri = ImageEnhance.Brightness(self.image) brightness = 1.4 image_brightened = enh_bri.enhance(brightness) image_brightened.save('E:\\captcha\\aa.png') # 色度增強 def Color_img(self): enh_col
= ImageEnhance.Color(self.image) color = 1.5 image_colored = enh_col.enhance(color) image_colored.save('E:\\captcha\\bb.png') # 對比度增強 def Contrast_img(self): enh_con = ImageEnhance.Contrast(self.image) contrast = 1.5 image_contrasted = enh_con.enhance(contrast) image_contrasted.save('E:\\captcha\\cc.png') # 銳度增強 def Sharpness_img(self): enh_sha = ImageEnhance.Sharpness(self.image) sharpness = 3.0 image_sharped = enh_sha.enhance(sharpness) image_sharped.save('E:\\captcha\\dd.png') # 亮度增強對比度增強 def Brightness_And_Contrast_img(self): enh_bri = ImageEnhance.Brightness(self.image) brightness = 1.4 image_brightened = enh_bri.enhance(brightness) enh_con = ImageEnhance.Contrast(image_brightened) contrast = 1.5 image_contrasted = enh_con.enhance(contrast) image_contrasted.save('E:\\captcha\\Ee.png') if __name__ == '__main__': img_x = ImageAugument('img.png') img_x.Brightness_And_Contrast_img()

具體數值可以通過aa bb cc dd去檢視哪張圖驗證碼更清晰,引數可自行調整

 

4.使用第三方庫識別圖片中的驗證碼:

博豬最開始用:pillow+pytesseract;優點是免費,較為易用,但其識別精度一般。

但是!我發現了一個第三方庫,該庫名也是非常有趣 —— ddddocr(諧音帶帶弟弟OCR)

Github地址:https://github.com/sml2h3/ddddocr

環境要求

python >= 3.8

Windows/Linux/Macox..

可以通過pip命令安裝:

以下是程式碼,五行識別驗證碼

import ddddocr

ocr = ddddocr.DdddOcr()
with open('1.png', 'rb') as f:
    img_bytes = f.read()
res = ocr.classification(img_bytes)

print(res)