# !/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2019/12/19 13:05
# @Author : ljf
# @File : youdao.py
import requests
import time
import hashlib
import random
class youdao_crawl:
def __init__(self):
"""
初始化内容
"""
self.url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
'Referer': 'http://fanyi.youdao.com/',
'Cookie': 'YOUDAO_MOBILE_ACCESS_TYPE=1; [email protected]; OUTFOX_SEARCH_USER_ID_NCOO=62105739.76007765; JSESSIONID=aaaNhy9FAvO3l7Ye5HC8w; ___rl__test__cookies=1576732583589'
}
self.data = {
'i': None,
'from': 'AUTO',
'to': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': None,
'sign': None,
'ts': None,
'bv': None,
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_REALTlME'
}
# def language(self, original, translate):
# """
# Args:
# original: 原始语言
# translate: 翻译语言
# Returns: 无
# """
# type = {
# 'AUTO': 'AUTO',
# '中文': 'zh-CHS',
# '英语': 'en',
# '日语': 'ja',
# '韩语': 'ko',
# '法语': 'fr',
# '德语': 'de',
# '俄语': 'ru',
# '西班牙语': 'es',
# '葡萄牙语': 'pt',
# '意大利语': 'it',
# '越南语': 'vi',
# '印尼语': 'id',
# '阿拉伯语': 'ar',
# }
# self.data['from'] = type[original]
# self.data['to'] = type[translate]
def translate(self, word):
"""
Args:
word: 要翻译的内容
Returns: 无
"""
ts = str(int(time.time()))
salt = str(int(time.time()) + random.random() * 10 + 10)
sign = 'fanyideskweb' + word + salt + 'n%A-rKaT5fb[Gy?;N5@Tj'
sign = hashlib.md5(sign.encode('utf-8')).hexdigest()
bv = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0'
bv = hashlib.md5(bv.encode('utf-8')).hexdigest()
self.data['i'] = word
self.data['salt'] = salt
self.data['sign'] = sign
self.data['ts'] = ts
self.data['bv'] = bv
# def run(self, original, translate, word):
# youdao.language(original,translate)
def run(self, word):
"""
Args:
word: 要翻译的内容
Returns: 翻译后的内容
"""
youdao.translate(word)
re = requests.post(self.url, headers=self.headers, data=self.data)
return re.json()['translateResult'][0][0].get('tgt')
if __name__ == '__main__':
youdao = youdao_crawl()
while True:
content = input("请输入您需要翻译的内容:")
if content == "q":
break
trans = youdao.run(content)
print(trans)