结合代理使用python调用有道翻译

# -*- coding: UTF-8 -*-
from urllib import request
import  random
import urllib.parse
import time
import urllib
import hashlib
import json

if __name__ == "__main__":

    # 访问网址
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'  
    # 这是代理IP
    proxy = [{'http': '139.224.24.26:8888'}]  # {'http':'121.41.6.85:3128'},{'http':'116.214.32.51:8080'},测试时可用,后来不能用
    # 创建ProxyHandler
    proxy_support = request.ProxyHandler(random.choice(proxy)) # 多个可用的代理时随机选择一个
    # 创建Opener
    opener = request.build_opener(proxy_support)
    # =====================================================================
    i = str(int(time.time() * 1000) + random.randint(1, 10))
    # t = input("please input the word you want to translate:")
    t = 'Is there anything else that is the same shape as the small brown matte object'
    u = 'fanyideskweb'
    l = 'ebSeFb%=XZ%T[KZ)c(sy!' # 不同的时间可能不同
    src = u + t + i + l  # u 与 l 是固定字符串,t是你要翻译的字符串,i是之前的时间戳

    m2 = hashlib.md5()
    m2.update(src.encode('utf8'))
    str_sent = m2.hexdigest()

    head = [
        ('Accept', 'application/json, text/javascript, */*; q=0.01'),
        ('Accept-Encoding', 'gzip, deflate'),
        ('Accept-Language', 'zh-CN,zh;q=0.9'),
        ('Content-Length', '218'),
        ('Connection', 'keep-alive'),
        ('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'),
        ('Host', 'fanyi.youdao.com'),
        ('Referer', 'http://fanyi.youdao.com/'),
        ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0'),
        ('X-Requested-With', 'XMLHttpRequest'),
        ('Cookie',
         'OUTFOX_SEARCH_USER_ID=1030453900@10.168.8.38; OUTFOX_SEARCH_USER_ID_NCOO=170893064.0436238;__rl__test__cookies=' + str(
             time.time() * 1000))
    ]
    data = {
        'i': t,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': i,
        'sign': str_sent,
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_CLICKBUTTION',  # FY_BY_CLICKBUTTION/FY_BY_REALTIME,两种方式都可以
        'typoResult': 'false'
    }
    # ======================================================================================================
    # 添加请求头
    opener.addheaders = head
    # 用opener来执行
    data = urllib.parse.urlencode(data).encode(encoding='UTF8')
    response = opener.open(url, data)
    # 读取相应信息并解码
    html = response.read().decode("utf-8")
    # count1 += 1
    result = json.loads(html)
    # 打印信息
    print(result['translateResult'][0][0]['tgt'])

参考内容:

python3 使用代理访问

Python 调用有道的翻译接口


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页