python练习6:对爬取的有道翻译功能进行改进

先上改进后的代码:

import urllib.request
import urllib.parse
import json


while True: # 实现连续翻译功能
    content = input('输入要翻译的内容: ')

    def trans(): # 把爬虫封装成一个函数
        url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        data = {
     }

        data['i'] = content
        data['from'] = 'AUTO'
        data['to'] = 'AUTO'
        data['smartresult'] = 'dict'
        data['client'] = 'fanyideskweb'
        data['salt'] = '15938760135952'
        data['sign'] = 'af3f1c36a96655e1a13616ec4e523d9c'
        data['ts'] = '1593876013595'
        data['bv'] = 'ce1fe729a12a6b5169046dd3aac11e4c'
        data['doctype'] = 'json'
        data['version'] = '2.1'
        data['keyfrom'] = 'fanyi.web'
        data['action'] = 'FY_BY_CLICKBUTTION'
        data = urllib.parse.urlencode(data).encode('utf-8')

        response = urllib.request.urlopen(url, data)
        html = response.read().decode('utf-8')
        target = json.loads(html)['translateResult'][0][0]['tgt']
        print('翻译结果: ', target)


    while content == '': #对用户输入情况进行判断,并循环提示
        content = input('重新输入要翻译的内容: ')
            
    else: # 如果用户输入内容不为空,调用封装的爬虫方法,把翻译结果输出给用户
        trans()

新增功能有:
1,当用户输入内容为空(即不输入内容),提示用户重新输入
2,当用户重新输入内容也为空时,继续提示用户重新输入
3,实现连续翻译功能

你可能感兴趣的:(python练习6:对爬取的有道翻译功能进行改进)