Python 20 simple lines achieve a proper way of translating online Comments

Brief introduction

The main is to try using a simple pyhton reptiles function, so use a proper way to try and not call-related such as depth of api.

The following is the POST data needed

Code

Here is the code of the relevant part:

import urllib.request
import urllib.parse
import json
'''
遇到python不懂的问题,可以加Python学习交流群:1004391443一起学习交流,群文件还有零基础入门的学习资料
'''
content=input('需要翻译的内容:')
#翻译内容
 
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionFrom=http://fanyi.youdao.com/'
#有道翻译查询入口
data = {  #表单数据
   'i': content,
   'from': 'AUTO',
   'to': 'AUTO',
   'smartresult': 'dict',
   'client': 'fanyideskweb',
   'doctype': 'json',
   'version': '2.1',
   'keyfrom': 'fanyi.web',
   'action': 'FY_BY_CLICKBUTTION',
   'typoResult': 'false'
  }
 
data=urllib.parse.urlencode(data).encode('utf-8')
#对POST数据进行编码
 
response=urllib.request.urlopen(url,data)
#发出POST请求并获取HTTP响应
 
html=response.read().decode('utf-8')
#获取网页内容,并进行解码解码
 
target=json.loads(html)
#json解析
 
print("\n翻译结果:%s"%target['translateResult'][0][0]['tgt'])
#输出翻译结果

 

Important function

urllib.request.urlopen () - POST data transmission, and returns the response

urllib.parse.urlencode () - encoded POST data conversion

json.loads () - json be resolved

Guess you like

Origin blog.csdn.net/qq_40925239/article/details/92629900