selenium破解數字驗證碼


 

 

搞了半天,總算弄出來了,識別率還可以,普通的數字驗證碼

 

from selenium import webdriver
from PIL import Image
import pytesseract
import PIL.ImageOps
import time

driver = webdriver.Chrome()

url = ''
driver.implicitly_wait(10)
driver.get(url)
driver.find_element_by_xpath('//*[@id="1_5"]').click()  # 點擊第三個
driver.find_element_by_xpath('//*[@id="4_organname"]').send_keys('代理')  # 輸入代理

driver.save_screenshot('f.jpg')  # 獲取網頁的截圖
imgelement = driver.find_element_by_id('cx5')  # 通過id定位驗證碼
location = imgelement.location  # 獲取驗證碼的x,y軸
size = imgelement.size  # 獲取驗證碼的長寬
rangle = (int(location['x']),
          int(location['y']),
          int(location['x']) + size['width'],
          int(location['y']) + size['height'],)  # 我們需要截取的驗證碼坐標

i = Image.open('f.jpg')#整張網頁
verifycodeimage = i.crop(rangle)  # 從網頁截圖截取驗證碼區域
verifycodeimage.save('f2.jpg')
im = Image.open('f2.jpg')#驗證碼區域
im.show()

#、二值化處理

# 二值化是圖像分割的一種常用方法。在二值化圖象的時候把大於某個臨界灰度值的像素灰度設為灰度極大值,
# 把小於這個值的像素灰度設為灰度極小值,從而實現二值化(一般設置為0-1)。根據閾值選取的不同,二值化的算法分為固定閾值和自適應閾值,
# 這里選用比較簡單的固定閾值。把像素點大於閾值的設置,1,小於閾值的設置為0。生成一張查找表,再調用point()進行映射。
def initTable(threshold=140):
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    return table


im = im.convert('L')#轉換為灰色圖像
binaryImage = im.point(initTable(), '1')
im1 = binaryImage.convert('L')
im2 = PIL.ImageOps.invert(im1)
im3 = im2.convert('1')
im4 = im3.convert('L')
# 將圖片中字符裁剪保留
box = (5, 2, 57, 17)#這個參數改了半天   第一個參數是放大右邊的,第二個是放大下邊的,第三個參數是左右的大小,數越大越往左邊縮,最后一個參數是上下的大小,數越大越往上面縮
 region = im4.crop(box) # 將圖片字符放大 out = region.resize((120, 38)) testdata_dir_config = '--tessdata-dir "C:\\Program Files\\Tesseract-OCR\\tessdata"' out.show() asd = pytesseract.image_to_string(out, config=testdata_dir_config) # 拿到驗證碼 textcode = asd.replace(' ', '') # 過濾空格 print(textcode) time.sleep(2) driver.find_element_by_xpath('//*[@id="valcode4"]').send_keys(textcode) # 輸入驗證碼 driver.find_element_by_xpath('//*[@id="tab_1_5"]/ul/li[4]/img[1]').click() # 點擊查詢

 


免責聲明!

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



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