python 获取openapi
时间: 2023-11-10 22:48:45 浏览: 36
获取OpenAPI需要以下步骤:
1. 首先去OpenAPI的官网注册开发者账号,获取API Key和Secret Key。
2. 安装Python的requests库,用于发送HTTP请求。
3. 通过requests库向OpenAPI发送HTTP请求,获取API返回的数据。
以下是一个获取OpenAPI数据的示例代码:
```python
import requests
import json
# 替换为自己的API Key和Secret Key
api_key = 'your_api_key'
secret_key = 'your_secret_key'
# 获取Token
url = 'https://openapi.baidu.com/oauth/2.0/token'
params = {'grant_type': 'client_credentials', 'client_id': api_key, 'client_secret': secret_key}
response = requests.post(url, params=params)
access_token = json.loads(response.text)['access_token']
# 获取API数据
url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify'
headers = {'Content-Type': 'application/json'}
params = {
'text': '今天天气真好',
}
data = json.dumps(params)
response = requests.post(url + '?access_token=' + access_token, headers=headers, data=data)
result = json.loads(response.text)
print(result)
```
在上面的示例代码中,我们首先通过API Key和Secret Key获取了Access Token,然后再使用Access Token向OpenAPI发送HTTP请求,获得了情感分析的结果。你可以根据自己的需求修改代码中的参数和API接口。