Python自動識別驗證碼


前言

這個是在網上找的代碼修修改改之后發現還是蠻好用的。成功率在60%左右,雖然成功率雖然有點低,但是相對來說還是蠻可以的了。

 1 import re
 2 from PIL import Image
 3 import pytesseract
 4  
 5  
 6 # 自動識別驗證碼
 7 def get_pictures(driver):
 8     # 整個頁面截圖的圖片存放路徑
 9     driver.save_screenshot(r'D:\Honest\picture\poo1.png')
10     # id是驗證碼在頁面上的id
11     pg = driver.find_element_by_id('codeImg')
12     left = pg.location['x']
13     top = pg.location['y']
14     right = pg.size['width'] + left
15     height = pg.size['height'] + top
16     im = Image.open(r'D:\Honest\picture\poo1.png')
17     image_obj = im.crop((left, top, right, height))
18     # 驗證碼截圖的圖片存放路徑
19     image_obj.save(r'D:\Honest\picture\poo2.png')
20     images = image_obj.convert("L")  # 轉灰度
21     pixdata = images.load()
22     w, h = images.size
23     # 像素值
24     threshold = 190
25     # 遍歷所有像素,大於閾值的為黑色
26     for y in range(h):
27         for x in range(w):
28             if pixdata[x, y] < threshold:
29                 pixdata[x, y] = 0
30             else:
31                 pixdata[x, y] = 255
32     data = images.getdata()
33     w, h = images.size
34     black_point = 0
35     for x in range(1, w - 1):
36         for y in range(1, h - 1):
37             mid_pixel = data[w * y + x]  # 中央像素點像素值
38             if mid_pixel < 50:  # 找出上下左右四個方向像素點像素值
39                 top_pixel = data[w * (y - 1) + x]
40                 left_pixel = data[w * y + (x - 1)]
41                 down_pixel = data[w * (y + 1) + x]
42                 right_pixel = data[w * y + (x + 1)]
43                 # 判斷上下左右的黑色像素點總個數
44                 if top_pixel < 10:
45                     black_point += 1
46                 if left_pixel < 10:
47                     black_point += 1
48                 if down_pixel < 10:
49                     black_point += 1
50                 if right_pixel < 10:
51                     black_point += 1
52                 if black_point < 1:
53                     images.putpixel((x, y), 255)
54                 black_point = 0
55     result = pytesseract.image_to_string(images)  # 圖片轉文字
56     resultj = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", result)  # 去除識別出來的特殊字符
57     result_four = resultj[0:4]  # 只獲取前4個字符
58     # print(result_four)  # 打印識別的驗證碼
59     return result_four

 調用例子:

from selenium import webdriver
from common.common_verification import get_pictures # 方法路徑
 
 
def test_a():
    driver = webdriver.Chrome()
    driver.get(r"www.123.com")
    # 賬號
    driver.find_element_by_name('loginname').send_keys('123')
    # 密碼
    driver.find_element_by_name('password').send_keys('123')
    # 驗證碼  調用方法 get_pictures(self.driver)
    driver.find_element_by_id('code').send_keys(get_pictures(self.driver))
 
if __name__ == '__main__':
    test_a()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM