欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python教你简单实现有道翻译

程序员文章站 2024-03-17 18:54:28
...

python教你简单实现有道翻译

话不多说,直接上代码

import requests
import time
import random
import hashlib
import json


class YouDaoSpider():
    def __init__(self):
        self.url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
        # 添加refer和cookie信息**反爬
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36",
            "Referer": "http://fanyi.youdao.com/",
            "Cookie": "[email protected]; JSESSIONID=aaaCq3pd7ZJl54AbdowMw; OUTFOX_SEARCH_USER_ID_NCOO=1716839688.6968515; DICT_UGC=be3af0da19b5c5e6aa4e17bd8d90b28a|; JSESSIONID=abcDebZ7HoIN6c2KhowMw; _ntes_nnid=9514c5286c5ea1293307a71dac676426,1553003612088; ___rl__test__cookies=1553009222487"
        }

    def get_post_data(self, content):
        """准备post数据"""
        salt = str(int(time.time() * 1000) + random.randint(1, 10))
        sign = hashlib.md5(("fanyideskweb" + content + salt + "1L5ja}[email protected]").encode('utf-8')).hexdigest()
        data = {
            "i": content,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": salt,
            "sign": sign,
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTlME",
            "typoResult": "false",
        }
        return data

    def parse_url(self, post_data):
        """发送请求获取响应"""
        response = requests.post(self.url, data=post_data, headers=self.headers)
        return response.content.decode('utf-8')

    def get_content(self, html_str):
        """获取数据"""
        json_data = json.loads(html_str)
        res = json_data['translateResult'][0][0]['tgt']
        return res

    def run(self, content):
        # 1.准备post_data
        post_data = self.get_post_data(content)
        # 2.发送请求
        html_str = self.parse_url(post_data)
        # 3.获取结果
        res = self.get_content(html_str)
        return res


if __name__ == '__main__':
    content = input("请输入你要翻译的内容>>")
    youdao_spider = YouDaoSpider()
    res = youdao_spider.run(content)
    print(res)