利用URL拼接爬取获取有道翻译内容
代码:
import requests
import chardet
import jsonif __name__ == '__main__':i = input('请输入要翻译的内容:')url = 'http://fanyi.youdao.com/translate?i=%s&smartresult=dict&smartresult=rule' % idata = {'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'])
运行结果: