美文网首页
Python调用有道翻译

Python调用有道翻译

作者: TMAC_EAH | 来源:发表于2018-02-23 17:30 被阅读0次
import requests
import json
import time
import hashlib
import random
if __name__ == '__main__':
    S = requests.Session()
    target_url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    # http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
    target_headers = {
        # 'Referer':'http://fanyi.youdao.com/',
        # 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        # 'Origin':'http//fanyi.youdao.com',
        # 'Host':'fanyi.youdao.com',
        # 'Accept':'application/json, text/javascript, *',
        # 'Accept':'application/json, text/javascript, */*; q=0.01',
        # 'Connection':'keep-alive',
        # 'Accept-Language':'zh-cn',
        # 'Accept-Encoding':'gzip, deflate',
        # 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/604.5.6 (KHTML, like Gecko) Version/11.0.3 Safari/604.5.6',
        # 'X-Requested-With':'XMLHttpRequest',
        # 'Proxy-Connection':'keep-alive',
        # ============================
        # 'Accept':'application/json, text/javascript, */*; q=0.01',
        # 'Accept-Encoding':'gzip, deflate',
        # 'Accept-Language':'zh-CN,zh;q=0.9',
        # 'Content-Length':'200',
        # 'Connection':'keep-alive',
        # 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
        # 'Host':'fanyi.youdao.com',
        # 'Origin':'http://fanyi.youdao.com',
        'Referer':'http://fanyi.youdao.com/',
        'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36',
        # 'X-Requested-With':'XMLHttpRequest',
    }
    # salt = var r = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10));
    r = str(int(time.time()*1000)+random.randint(1,10))
    t = "接口"

    # sign = n.md5("fanyideskweb" + t + r + "ebSeFb%=XZ%T[KZ)c(sy!");
    src = "fanyideskweb" + t + r + "ebSeFb%=XZ%T[KZ)c(sy!";
    print("src=%s"%src)
    tank = hashlib.md5()
    tank.update(src.encode("utf8"))
    # TypeError: Unicode-objects must be encoded before hashing
    # sign = hashlib.md5().update(src.encoded("utf8")).hexdigest();#这样不行
    # AttributeError: 'str' object has no attribute 'encoded'
    # sign = hashlib.md5().update(src.encode("utf8")).hexdigest();
    sign = tank.hexdigest();
    print("i=%s"%t)
    print("salt=%s"%r)
    print("sign=%s"%sign)
    # Form_Data = {}
    # Form_Data['from'] = 'AUTO'
    # Form_Data['to'] = 'AUTO'
    # Form_Data['smartresult'] = 'dict'
    # Form_Data['client'] = 'fanyideskweb'
    # Form_Data['salt'] = r
    # Form_Data['sign'] = sign
    # Form_Data['i'] = t
    # Form_Data['doctype'] = 'json'
    # Form_Data['version'] = '2.1'
    # Form_Data['keyfrom'] = 'fanyi.web'
    # #Form_Data['ue'] = 'ue:UTF-8'
    # Form_Data['action'] = 'FY_BY_CLICKBUTTON'
    # Form_Data['typoResult'] = 'false'
    Form_Data = {
        'i': t,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': r,
        'sign': sign,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',
        'typoResult': 'false'
    }
    #  1519371677462 = 时间戳
    target_headers['Cookie']= '___rl__test__cookies=1519371677462; fanyi-ad-closed=1; fanyi-ad-id=40789; JSESSIONID=aaaJ0epv-u81l5kbPSahw; OUTFOX_SEARCH_USER_ID=-1436919211@10.168.8.61; _ga=GA1.2.75737907.1502714379; OUTFOX_SEARCH_USER_ID_NCOO=685806044.3219135'
    # target_response = S.post(url = target_url, data = Form_Data, headers = target_headers)
    target_response = S.post(url=target_url, data = Form_Data, headers = target_headers)
    print (target_response.text)
    # html = target_response.text
    translateResult = json.loads(target_response.text)
    print ("翻译返回是:%s"%translateResult)
    print ("翻译返回是:%s"%translateResult['translateResult'][0])
    print ("翻译返回是:%s"%translateResult['translateResult'][0][0]['tgt'])

经过试验 必须带三个头,其它可以不带

Referer 
User-Agent 
Cookie

否则

{'errorCode': 50}

调用结果

src=fanyideskweb接口1519377881105ebSeFb%=XZ%T[KZ)c(sy!
i=接口
salt=1519377881105
sign=0f4a99fedc56b5b99d4521aea0a85ee9
{"translateResult":[[{"tgt":"interface","src":"接口"}]],"errorCode":0,"type":"zh-CHS2en","smartResult":{"entries":["","port\r\n","connector\r\n","hickey\r\n"],"type":1}}
翻译返回是:{'translateResult': [[{'tgt': 'interface', 'src': '接口'}]], 'errorCode': 0, 'type': 'zh-CHS2en', 'smartResult': {'entries': ['', 'port\r\n', 'connector\r\n', 'hickey\r\n'], 'type': 1}}
翻译返回是:[{'tgt': 'interface', 'src': '接口'}]
翻译返回是:interface
[Finished in 1.0s]

sign 和 salt 核心代码 js

t.asyRequest = function(e) {
        var t = e.i,
            i = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10)),
            o = n.md5("fanyideskweb" + t + i + "ebSeFb%=XZ%T[KZ)c(sy!");
        r && r.abort(), r = n.ajax({
            type: "POST",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            url: "/bbk/translate_m.do",
            data: {
                i: e.i,
                client: "fanyideskweb",
                salt: i,
                sign: o,
                tgt: e.tgt,
                from: e.from,
                to: e.to,
                doctype: "json",
                version: "3.0",
                cache: !0
            },
            dataType: "json",
            success: function(t) {
                t && 0 == t.errorCode ? e.success && e.success(t) : e.error && e.error(t)
            },
            error: function(e) {}
        })
    }

参考地址

ps:2018-2-23日测试有效

相关文章

网友评论

      本文标题:Python调用有道翻译

      本文链接:https://www.haomeiwen.com/subject/mqwxxftx.html