import requests
import json
# 1. url
url = 'http://fanyi.baidu.com/sug'
# 2. form/ data/ body
def translate(kw):
form = {
'kw': kw
}
# # 2.1 字典转换成str
# form_str = parse.urlencode(form)
# #print(form_str)
# # 2.2 str转换成bytes
# form_bytes = form_str.encode('utf-8')
# # 3. 调用函数 url form
# response = request.urlopen(url, data=form_bytes)
# request 的post方法色使用
response = requests.post(url, data=form)
# str = response.content.decode('utf-8/gbk/gb2312/gb18080') =
response.encoding = 'utf-8/gbk/gb2312/gb18080'
str = response.text
# 4. 解析json
res_dict = json.loads(response.text)
# 5. 打印翻译结果
#print(res_dict)
result = res_dict['data'][0]['v']
return result
if __name__ == '__main__':
res = translate('哈哈')
print(res)
转载于:https://www.cnblogs.com/wopuchezhan/p/9526473.html