爬蟲遇到驗證碼應該怎么解決?Python反反爬教學
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
一 前言
中國知網的注冊頁面使用的是這種驗證碼,頁面如下:
二 準備作業
1 目標
以知網的驗證碼為例,利用OCR(Optical Character Recognition 光學字符識別)技術識別圖形驗證碼,
2 安裝tesseract
2.2 下載tesseract-ocr-setup-3.05.01.exe
2.3 安裝注意事項
勾選Additional language data(download)選項,這樣可以識別多國語言,
3 安裝tesserocr
pip install tesserocr pillow
安裝好的Tesseract-OCR后,從D:\Program Files (x86)\Tesseract-OCR目錄下,將tessdata檔案夾拷貝到下面目錄
E:\WebSpider\venv\Scripts
4 獲取驗證碼
將驗證碼圖形 保存到本地,命名為code.jpg
三 實戰
1 實戰
1.1 代碼
import tesserocr
from PIL import Image
image = Image.open('code.jpg')
result = tesserocr.image_to_text(image)
print(result)
image = Image.open('code1.jpg')
result = tesserocr.image_to_text(image)
print(result)
image = Image.open('code2.jpg')
result = tesserocr.image_to_text(image)
print(result)
1.2 效果
E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
DTKD
JR42
PFRT
1.3 說明
code.jpg是DTKT
code1.jpg是JR42
code2.jpg是PFRT
將結果和實際圖片進行比較,正確率還是比較高的,
2 實戰2
2.1 代碼
import tesserocr
print(tesserocr.file_to_text('code.jpg'))
print(tesserocr.file_to_text('code1.jpg'))
print(tesserocr.file_to_text('code2.jpg'))
2.2 效果
E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
DTKD
.ll?42
FFKT
2.3 說明
code.jpg是DTKT
code1.jpg是JR42
code2.jpg是PFRT
將結果和實際圖片進行比較,正確率并不是很高,
3 實戰3
3.1 代碼
import tesserocr
from PIL import Image
image = Image.open('code2.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')
image.show()
result = tesserocr.image_to_text(image)
print(result)
3.2 效果
E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
PFRT
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/189495.html
標籤:Python
上一篇:程式員學習必備書單匯總,超全!
