有道智云 之翻译网页内容

一、文档

https://ai.youdao.com/DOCSIRMA/html/trans/api/wyfy/index.html

二、示例

# -*- coding: utf-8 -*-
import sys
import uuid
import requests
import hashlib
import time
from importlib import reload
import json

import time

reload(sys)

# 有道翻译地址
YOUDAO_URL = 'https://openapi.youdao.com/translate_html'
# 替换为您的应用ID
APP_KEY = ''
# 替换为您的密钥
APP_SECRET = ''

''' sha256加密 '''
def encrypt(signStr):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(signStr.encode('utf-8'))
    return hash_algorithm.hexdigest()

''' 判断长度 '''
def truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]

''' 开始翻译 '''
def do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)

def connect(keywords, to='en', _from='zh-CHS'):
    if not keywords:
        return ''
    q = keywords
    data = {}
    data['from'] = _from
    data['to'] = to
    data['signType'] = 'v3'
    curtime = str(int(time.time()))
    data['curtime'] = curtime
    salt = str(uuid.uuid1())
    signStr = APP_KEY + truncate(q) + salt + curtime + APP_SECRET
    sign = encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = q
    data['salt'] = salt
    data['sign'] = sign

    response = do_request(data)
    contentType = response.headers['Content-Type']
    if contentType == "audio/mp3":
        millis = int(round(time.time() * 1000))
        filePath = "合成的音频存储路径" + str(millis) + ".mp3"
        fo = open(filePath, 'wb')
        fo.write(response.content)
        fo.close()
    else:
        json_obj = json.loads(response.content)
        # print(json_obj)
        if json_obj.get('errorCode') == '0':
            return json_obj.get('data').get('translation')
        elif json_obj.get('errorCode') == '500':
            if json_obj.get('errorMessage') == '30':
                # 翻译失败
                return q
            print("errorMessage = " + json_obj.get('errorMessage'))
        # 其他情况返回空
        return ''

if __name__ == '__main__':
    data = connect("公司专业生产的PVC套管", 'en')
    print(data)

 

posted @ 2023-06-02 09:48  样子2018  阅读(66)  评论(0编辑  收藏  举报