from urllib import request
import re
import urllib
import time
#用户接口输入
key = input("请输入你需要翻译的内容:")
#构造请求头
header = {
"User-Agent": "Mozilla/5.0 (Linux; U; An\
droid 8.1.0; zh-cn; BLA-AL00 Build/HUAW\
EIBLA-AL00) AppleWebKit/537.36 (KHTML, l\
ike Gecko) Version/4.0 Chrome/57.0.2987.13\
2 MQQBrowser/8.9 Mobile Safari/537.36"
}
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
# http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule
#请求需要提的参数
formdata = {
"i": key,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": "16015394116381",
"sign": "fe0a349864c8e04f1219d8d4465eb042",
"lts": "1601539411638",
"bv": "52dd8074f15d3797000a252ed2659a35",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_REALTlME"}
#经过urlencode转码
data = urllib.parse.urlencode(formdata).encode(encoding="utf8")
req = request.Request(url,data=data,headers=header)
resp = request.urlopen(req).read().decode()
#正则表达式 提取:"tgt":"和"}]]中间的任意内容
pat = r‘"tgt":"(.*?)"}]]‘ #(.*?) 任意内容
#"translateResult":[[{"src":"我爱你","tgt":"I love you"}]]}
result = re.findall(pat,resp)
#print(resp)
print("翻译结果:",result[0])
人生苦短,我用Python------自学python三周小爬虫,借助有道翻译写成翻译软件
原文:https://www.cnblogs.com/-pythom/p/13759240.html