1. 程式人生 > >Python爬蟲專案實戰3 | 圖片文字識別(以驗證碼識別為例)

Python爬蟲專案實戰3 | 圖片文字識別(以驗證碼識別為例)

1.專案背景

我在實習過程中,當我抓取環保平臺相關資料時,常常發現有圖片的情況,比如以下這種圖片,所以抓取這種圖片中的資訊是我進行圖片文字識別的動力:

2.專案思路

因為在某一網站中有大量這種想要抓取的圖片,所以我的思路是,

1.先抓取這些圖片的名稱和URL;

2.然後再根據這些URL得到圖片資訊;

3.然後識別資訊。

3.驗證碼圖片識別示例

【1】首先,我們可以找一個有很多驗證碼的網站,比如:驗證碼處理網站;從網站頁面原始碼(在網站中右鍵)中找到圖片的URL,以及他們的名稱,然後將這些圖片下載下來,程式碼如下:

spicerman.py

import re
import requests
from bs4 import BeautifulSoup
import chardet
from urllib import parse

url = 'https://captcha.com/captcha-examples.html?cst=corg'
user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:63.0) Gecko/20100101 Firefox/63.0'
headers = {
    'User-Agent': user_agent
}
response = requests.get(url, headers=headers, timeout=10)
response.encoding = chardet.detect(response.content)['encoding']
html = response.text
soup = BeautifulSoup(html, 'lxml')

# 提取我們想要的資訊,即圖片資訊
image_list = soup.find_all(name='img', class_='captcha_sample')
image_names = soup.find_all(name='h3')

image_urls = list()
seq = 0
for image in image_list:
    image_url = parse.urljoin(url, image['src'])
    image_urls.append(image_url)
    print(image_url)
    with open("urls.txt", 'a') as fout:
        fout.write(image_url)
        fout.write('\n')
    # 根據url下載圖片
    try:
        url_res = requests.get(image_url, headers=headers, timeout=10)
        if url_res.status_code == 200:
            name = image_names[seq].text + '.jpg'
            with open(name, 'wb') as fout:
                fout.write(url_res.content)
                print('第{}圖片下載成功!'.format(seq))
    except Exception as e:
        print(e)

    seq += 1


 【2】然後,我們可以藉助百度的圖片識別模組來處理,百度AI開放平臺的連結為:http://ai.baidu.com。在網頁右上角的控制檯登入,之後會顯示如下:

【3】看到左側有“文字識別”的選單,按一下:

【4】然後建立應用,名字隨意,建立後,會顯示如下網頁資訊,在網頁中有應用的AppID,APIKey和Secret Key:

 【5】使用上述的資訊,我們便可以使用百度的圖片識別啦,模組為aip, 在終端安裝為pip3 install aip。當然,關於模組的文件可在網站中找到,不再贅述。

實現的recognizer.py如下:

from aip import AipOcr

# 填入你自己的資訊
APP_ID = '1××××××8'
API_KEY = 'k×××××××××××××××××h81'
SECRET_KEY = 'a×××××××××××××××××××××KV'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


# 讀取圖片
def get_file_content(filepath):
    with open(filepath, 'rb') as fp:
        return fp.read()

# 呼叫通用文字識別,圖片引數為本地圖片
image = get_file_content('Wave Captcha Image.jpg')
# 定義引數變數
options = {
    # 定義影象方向
    'detect-direction': 'true',
    'language-type': 'CHN_ENG'
}
result = client.general(image, options)
print(result)
for word in result['words_result']:
    print(word['words'])

【6】在控制檯便顯示圖片中的資訊啦~

如下是我識別最前面圖片中的資訊: