利用URL拼接爬取获取有道翻译内容
代码:
import requests
import chardet
import json
if __name__ == '__main__':
i = input('请输入要翻译的内容:')
url = 'http://fanyi.youdao.com/translate?i=%s&smartresult=dict&smartresult=rule' % i
data = {
'from': 'AUTO',
'to': 'AUTO',
'doctype': 'json',
'smartresult': 'dict',
'client': 'fanyideskweb',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTIME',
'TypoResult': 'false'
}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
' AppleWebKit/537.36 (KHTML, like Gecko)'
' Chrome/73.0.3683.86 Safari/537.36'
}
response = requests.post(url, data=data, headers=headers)
html = response.content # 读取返回的对象
code = chardet.detect(html) # 自行判断编码格式
data = html.decode(code.get('encoding', 'utf-8')) # 解码
json_data = json.loads(data) # 解析载入json数据
# print(json_data)
print('翻译的结果为:' + json_data['translateResult'][0][0]['tgt'])
运行结果: