1、开启baidu-api的文字识别
2、查看官方文档
3、例子
import time import pymysql import requests from aip import AipOcr from config import dev_db from config import APP_ID, API_KEY, SECRET_KEY # class Word: def __init__(self): self.host = dev_db.get('host') self.user = dev_db.get('user') self.password = dev_db.get('password') self.database = dev_db.get('database') self.APP_ID = APP_ID self.API_KEY = API_KEY self.SECRET_KEY = SECRET_KEY # self.url = self.get_url() # 从数据库中获取url def get_url(self): conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置游标卡尺和fetc的格式 sql = "select url from code order by id desc limit 1" # sql语句,分页 cursor.execute(sql) # list tuple dict ret = cursor.fetchone() # 取所有值 cursor.close() # 关闭游标卡尺 conn.close() # 关闭连接 url = ret.get('url') return url # 获取图片的数据 def get_file_content(self): response = requests.get(self.get_url()).content return response # 通过baidu-api识别图片 def get_word(self): client = AipOcr(self.APP_ID, self.API_KEY, self.SECRET_KEY) img = self.get_file_content() """ 调用网络图片文字识别, 图片参数为本地图片 """ ret = client.webImage(img) try: word = ret.get('words_result')[0].get('words') except: word = '' return word # 判断识别的结果是否为空和长度为4位 def judge(self): time.sleep(2) word = self.get_word() if len(word) == 4: print(word) return word else: self.judge() # 将识别的数据更新到数据库中 def update_sql(self): conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database) word = self.judge() print(type(word)) time.sleep(2) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) sql = 'update code set word =%s where url=%s' cursor.execute(sql, [word, self.get_url()]) conn.commit() cursor.close() conn.close() if __name__ == '__main__': # ret = baidu_discern('code.png') # print('=' * 100) # print(ret) w = Word() # a = w.get_url() # print(a) # w.get_file_content() # word = w.get_word() # print(word) w.update_sql()