有道翻译爬虫小demo

import urllib.request
import json
import urllib.parse
import sys
import random

while True:
    str = input("请输入要翻译的内容(输入0退出程序):")

    if str == '0':
        sys.exit(0)

    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    # 代理IP
    ip_list = [{'https':'125.126.110.182:60004'},{'https': '125.126.109.20:60004'},{'https':'125.126.115.116:60004'}]

    # 设置代理
    proxy_support = urllib.request.ProxyHandler(ip_list[random.randint(0,2)])
    opener = urllib.request.build_opener(proxy_support)

    # 设置请求头
    opener.addheaders = [('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36')]
    urllib.request.install_opener(opener)

    # data 数据
    data = {}
    data['to'] = 'AUTO'
    data['i'] = str
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['from'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['action'] = 'FY_BY_CLICKBUTTION'

    # 对data数据进行编码
    data = urllib.parse.urlencode(data).encode('utf-8')

    # 发起请求
    response = urllib.request.urlopen(url, data)

    # 读取响应数据,并解码
    html = response.read().decode('utf-8')

    # 将响应数据解析为json数据
    json_html = json.loads(html)
    print('翻译结果:%s' % json_html['translateResult'][0][0]['tgt'])
本文作者: Author:     文章标题: Python 有道翻译爬虫小demo
本文地址: https://codewei.cn/archives/206/      
版权说明:若无注明,本文皆为“阿伟的小屋”原创,转载请保留文章出处
Last modification:July 8th, 2020 at 03:14 pm
贫困山区儿童,谢谢打赏