(简单)实现翻译功能
要使用到的库
-
json
-
requests
json
- json
- -数据交换格式,看起来像Python类型(列表,字典)的字符串
- -使用之前要导入(import json)
- -把json字符串转化为Python类型
- -json.loads(json字符串)
- -json.dumps
- -把Python类型转化为json字符串
- -json.dumps({"y","88","d"})
1、首先打开网址 http://fanyi.sogou.com/
2、查看 response
3、查看 headers 并设置要传递的参数
1 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36','Referer': 'http://fanyi.sogou.com/'}
5、查看data参数 并设置要传递的参数data
1 text = input("请输入要翻译的内容...") 2 data = {'from': 'auto','to': 'en','client': 'pc','fr': 'browser_pc','text': text,'useDetect': 'on','useDetectResult': 'on','needQc': '1','uuid': '2d9c20da-29b2-4d2e-ab24-f0f431d38a33','oxford': 'on','isReturnSugg': 'off'}
源代码如下:
1 import requests 2 import json 3 4 text = input("请输入要翻译的内容...") 5 url = "http://fanyi.sogou.com/reventondc/translate" 6 data = {'from': 'auto','to': 'en','client': 'pc','fr': 'browser_pc','text': text,'useDetect': 'on','useDetectResult': 'on','needQc': '1','uuid': '2d9c20da-29b2-4d2e-ab24-f0f431d38a33','oxford': 'on','isReturnSugg': 'off'} 7 headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36','Referer': 'http://fanyi.sogou.com/'} 8 response = requests.post(url,data = data,headers = headers) 9 html_str = response.content.decode() 10 #json 解析 11 dict_ret = json.loads(html_str) 12 result = dict_ret['translate']['dit'] 13 14 print("翻译结果为:%s " % (result))