一、需求:
根据360在线翻译,获取免费API,并调用
二、主要步骤
1、请求 url
url = "https://fanyi.so.com/index/search"
2、传入信息
datas = {"query": "桌子"}
3、请求头
headers = {"pro": "fanyi","User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64"}
4、post请求:
response = requests.post(url, data=datas, headers=headers)
5、查看响应状态码
若为 200,即为响应成功。
6、解析响应信息与返回字符串
# 解析json
response = response.json()# 获取翻译信息
fanyi_ret = response["data"]["fanyi"]
三、完整代码:
import requests# 请求标头
headers = {"pro": "fanyi","User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64", }# 请求 url
url = "https://fanyi.so.com/index/search"def fanyi_360(datas):# 发送请求response = requests.post(url, data=datas, headers=headers)# 判断状态码if response.status_code == 200:# 解析jsonresponse = response.json()# 获取翻译信息fanyi_ret = response["data"]["fanyi"]return fanyi_retif __name__ == '__main__':# 传入参数datas = {"query": "桌子"}print(fanyi_360(datas))