1. 程式人生 > >python填坑之路:tesserocr配置

python填坑之路:tesserocr配置

    最近在學爬蟲,在模擬登入網站的時候常常需要輸入驗證碼,最常見的就是OCR(Optical Character Recognition,光學字元識別) ,於是乎瞭解到tesserocr這個庫,但是安裝的過程可謂坎坷。

    大致的過程可參考部落格:崔慶才的個人部落格,但是最好注意以下幾點

  1. 將tesseract(注意不是tesserocr)的安裝路徑加入環境變數。
  2. 將tesseract安裝目錄下的tessdata資料夾複製到你python的安裝路徑中去。如下

    3. 如果pip3 install tesserocr pillow失敗,考慮使用下載whl檔案安裝,可參考我之前的一篇博文

whl檔案版本選擇。

whl檔案下載地址:https://github.com/simonflueckiger/tesserocr-windows_build/releases

 

下面給出一個例項,我在爬取學校教務系統資料用到的,這個系統我後面有空會詳細展開,下面僅給出用於ocr部分的程式碼:

import requests
import os
import tesserocr
from PIL import Image
import re
from requests.exceptions import RequestException
headers ={
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}

def download_image(url):
    print('當前正在下載驗證碼圖片',url)
    try:
        response = requests.get(url,headers=headers)
        if response.status_code == 200:
            save_image(response.content)
        return None
    except RequestException:
        print('下載驗證碼圖片出錯',url)
        return None

def save_image(content):
    file_path = 'code.jpg'
    if os.path.exists(file_path):
        os.remove(file_path)
    with open(file_path,"wb") as f:
        f.write(content)
        f.close()

def get_ocr():
    download_image("http://csujwc.its.csu.edu.cn/verifycode.servlet")
    image = Image.open("code.jpg")
    image = image.convert('L')
    threshold = 127
    table =[]
    for i in range(256):
        if i<threshold:
            table.append(0)
        else:
            table.append(1)
    image = image.point(table,'1')
    result = tesserocr.image_to_text(image)
    result = re.sub('\s','',result)
    result = result.lower()
    if len(result)>4:
        result = result[0:4]
    print("result:"+result)
    return result

if __name__ =="__main__":
    get_ocr()