python模拟有道词典翻译文本

python模拟有道词典翻译文本

转载一个模拟有道词典翻译文本的脚本,学习一下

import urllib.request
import urllib.parse
import json
import time


while True:   
    content  =  input("请输入你想翻译的内容:")
    if content == 'q':
        braek
        
    #url中带—_o会导致{"errorCode":50}
    #url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    #获取浏览器类型的'User-Agent信息,避免禁止访问错误
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.1071 SLBChan/1'

    data = { }
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] =  'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '16137170355211'
    data['sign'] = '37d618ef49272a7dd5325e8a375b261b'
    data['lts'] = '1613717035521'
    data['bv'] = '8ec2482c48c5d4cf3ff41e80cd83571b'
    data['doctype'] =  'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_REALTlME'

    data = urllib.parse.urlencode(data).encode('utf-8')

    #实例化对象
    req = urllib.request.Request(url,data,head)
    response = urllib.request.urlopen(req)

    html = response.read().decode('utf-8')
    html_1 = json.loads(html)['translateResult'][0][0]['tgt']


    print("翻译结果—》" + html_1)

    time.sleep(2)

分享到 :

Leave a Reply

Your email address will not be published. Required fields are marked *