爬蟲-識別圖形驗證碼-tesserocr

引入:

  在學習爬蟲的過程當中,須要解決識別圖形驗證碼的這一難題,網上推薦的方法都是經過tesserocr模塊來實現,下面就是安裝步驟以及過程當中遇到的問題,記錄一下。python

介紹:

tesserocr 是 Python 的一個 OCR 識別庫 ,但實際上是對 tesseract 作的一 層 Python API 封裝,因此它的核心是 tesseract。 所以,在安裝 tesserocr 以前,咱們須要先安裝 tesseract 。例如:對於下圖的驗證碼,咱們能夠經過 OCR 技術將其轉換成電子文本,而後爬蟲將識別的結果提交給服務器,即可以達到自動識別驗證碼的過程。git

個人環境:

OS:win10github

python:3.6.5windows

相關連接

tesserocr GitHub: https://github.com/sirfz/tesserocr服務器

tesserocr PyPI: https://pypi.python.org/pypi/tesserocride

tesseract 下載地址: http://digi.bib.uni-mannheim.de/tesseract學習

tesseract GitHub: https://github.com/tesseract-ocr/tesseract測試

tesseract 語言包: http://github.com/tesseract-ocr/tessdataui

tesseract 文檔: https://github.com/tesseract-ocr/tesseract/wiki/Documentationspa

安裝

在 Windows 下,首先須要下載 tesseract,它爲 tesserocr 提供了支持。

進入下載頁面,能夠看到有各類 .exe 文件的下載列表,這裏能夠選擇下載 3.0 版本 。 以下圖所示爲 3.05 版本 。

 

其中文件名中帶有 dev 的爲開發版本,不帶 dev 的爲穩定版本,能夠選擇下載不帶 dev 的版本, 例如能夠選擇下載 tesseract-ocr-setup-3 .05.01.exe。 下載完成後雙擊運行,安裝程序。須要注意的是,須要句選 Additional language data(download)選項來安裝 OCR 識別支持的語言包,這樣 OCR 即可以識別多國語言 

給tesseract配置環境變量:

(1)將tesseract安裝路徑添加到path環境變量中

(2)將tesseract的語言包添加到環境變量中,在環境變量中新建一個系統變量,變量名稱爲TESSDATA_PREFIX,tessdata是放置語言包的文件夾,通常在你安裝tesseract的目錄下,tesseract的安裝目錄就是tessdata的父目錄,把TESSDATA_PREFIX的值設置爲它便可

接下來 , 再安裝 tesserocr :

pip install tesserocr pillow

pip安裝tesserocr時出錯:

在命令行中輸入:pip3 install tesserocr pillow ,一直出現error: Microsoft Visual C++ 14.0 is required. Get it with 「Microsoft Visual C++ Build Tools」: http://landinghub.visualstudio.com/visual-cpp-build-tools錯誤。

解決辦法:

用.whl文件下載tesserocr庫,就不會出現這個問題,下載地址:

https://github.com/simonflueckiger/tesserocr-windows_build/releases

我下載的是tesserocr-2.4.0-cp36-cp36m-win_amd64.whl,而後在命令行中輸入:

pip install tesserocr-2.4.0-cp36-cp36m-win_amd64.whl

安裝成功,問題解決

 

驗證安裝

測試樣例:

圖片下載:http://images.cnblogs.com/cnblogs_com/Jimc/1316973/o_image.png

(1)用 tesseract 命令測試:

tesseract test.png stdout -l eng

 運行結果以下:

 (2)利用 Python 代碼測試:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tesserocr >>> from PIL import Image >>> image = Image.open(r'C:\Users\Tianl\test.png') >>> result = tesserocr.image_to_text(image) >>> print(result) PythonWebSpider >>>

另外,還能夠直接調用 tesserocr 模塊的 file_to_text() 方法,能夠達到一樣的效果:

Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tesserocr >>> print(tesserocr.file_to_text(r'C:\Users\Tianl\test.png')) PythonWebSpider >>>

若是成功輸出結果,則證實 tesseract 和 tesserocr 都已經安裝成功,以上是安裝以及簡單使用。

 pycharm中安裝導入tesserocr

直接把上面經過pip安裝好的文件夾拷貝到pycharm建立的項目的site-packages目錄中便可使用

相關文章
相關標籤/搜索