import base64
import requests
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【AK】&client_secret=【SK】'
headers = {'Content-Type':'application/json; charset=UTF-8'}
response = requests.post(url=host,headers=headers)
con = response.json()
access_token = con['access_token']
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' + access_token
# 二进制方式打开图文件
f = open(r'身份证.jpg', 'rb')
# 参数image:图像base64编码
img = base64.b64encode(f.read())
params = {"image": img, "id_card_side": "front"}
headers = {'Content-Type':'application/x-www-form-urlencoded'}
respones = requests.post(url=url,data=params,headers=headers)
content = respones.json()
if content:
print(content)