1. 首页
  2. 编程语言
  3. Python
  4. 09-有道翻译POST.py教程及代码示例

09-有道翻译POST.py教程及代码示例

上传者: 2023-06-28 20:04:22上传 PY文件 1.24KB 热度 9次

Python代码示例:

import urllib.request

import urllib.parse

import json

请输入你要翻译的内容

key = input("请输入要翻译的内容:")

把提交的form表单数据转为bytes数据类型

data = {

"i": key,

"from": "AUTO",

"to": "AUTO",

"smartresult": "dict",

"client": "fanyideskweb",

"salt": "1540373170893",

"sign": "a5d9b838efd03c9b383dc1dccb742038",

"doctype": "json",

"version": "2.1",

"keyfrom": "fanyi.web",

"action": "FY_BY_REALTIME",

"typoResult": "false"

}

字符串i=python&from=

import urllib

请不要修改下面的代码,否则可能会导致运行错误。

url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

headers = {

'Accept': 'application/json, text/javascript, /; q=0.01',

# 'Accept-Encoding': 'gzip, deflate',

'Accept-Language': 'zh-CN,zh;q=0.9',

'Connection': 'keep-alive',

'Content-Length': '237',

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',

'Cookie': 'OUTFOX_SEARCH_USER_ID_NCOO=1847427800.8369298; OUTFOX_SEARCH_USER_ID="-1476835871@10.108.160.105"; _ntes_nnid=5a5a1cbca9182b09120824e51b990aad,1635039659726; JSESSIONID=aaa9Lc8ld6rEpYiQamBex; rl_testcookies=1635319399675',

'Host': 'fanyi.youdao.com',

'Origin': 'http://fanyi.youdao.com',

'Referer': 'http://fanyi.youdao.com/',

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',

'X-Requested-With': 'XMLHttpRequest',

}

data = urllib.parse.urlencode(data).encode('utf-8') # 将data转为bytes数据类型

req = urllib.request.Request(url, data=data, headers=headers)

response = urllib.request.urlopen(req)

html = response.read().decode('utf-8')

target = json.loads(html)

print('翻译结果:%s' % target['translateResult'][0][0]['tgt'])

用户评论