import urllib.request
import urllib.parse
#创建url
#地址一定要写对
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule '
form_data = {
'action': 'FY_BY_REALTlME',
'bv': '316dd52438d41a1d675c1d848edf4877',
'client' :'fanyideskweb',
'doctype': 'json',
'from' :'AUTO',
'i': 'baby',
'keyfrom' :'fanyi.web',
'salt' :'15583529043199',
'sign': '50854f3e3b8180d97371281ac0f7f851',#一个单词对应一个sign和ts
'smartresult' :'dict',
'to' :'AUTO',
'ts' :'1558352904319',
'version': '2.1',
}
headers = {
'Host': 'fanyi.youdao.com',
'Connection': 'keep-alive',
'Content-Length':'237',
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Origin': 'http://fanyi.youdao.com',
'X-Requested-With':'XMLHttpRequest',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Referer': 'http://fanyi.youdao.com/',
# 'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cookie': 'OUTFOX_SEARCH_USER_ID=-181098280@10.169.0.84; JSESSIONID=aaaKiWEaDPtbXcudjevRw; OUTFOX_SEARCH_USER_ID_NCOO=2076851833.794606; ___rl__test__cookies=1558352904316',
}
#构建请求对象
request=urllib.request.Request(url=url,headers=headers)
#处理表单数据
form_data=urllib.parse.urlencode(form_data).encode()
#发送请求
response = urllib.request.urlopen(request,data=form_data)
print(response.read().decode())
输出:{"translateResult":[[{"tgt":"婴儿","src":"baby"}]],"errorCode":0,"type":"en2zh-CHS","smartResult":{"entries":["","n. 婴儿,婴孩;孩子气的人 ","adj. 婴儿的;幼小的 ","vt. 纵容,娇纵;把……当婴儿般对待 "],"type":1}}
最后通过json解析得出:
{
"translateResult":[
[
{
"tgt":"婴儿",
"src":"baby"
}
]
],
"errorCode":0,
"type":"en2zh-CHS",
"smartResult":{
"entries":[
"",
"n. 婴儿,婴孩;孩子气的人 ",
"adj. 婴儿的;幼小的 ",
"vt. 纵容,娇纵;把……当婴儿般对待 "
],
"type":1
}
}