python 爬虫学习_有道翻译

python 爬虫_有道翻译代码如下:

import urllib.request
import urllib.parse
import json
import time


while True: 
    content = input('请输入需要翻译的内容(输入"q!"退出程序):')
    if content=='q!':
        break

    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
    #直接从审查元素中copy过来的url会报错,必须把translate_o中的_o 删除才可以
    #url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
    '''
    head={}
    head['User-Agent']='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'
    '''


    data = {}            #这里就是把 Form Data 中的内容贴过来
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '15930954560996'
    data['sign'] = '275d3cf1e0774156773586afbe7cde59'
    data['ts'] = '1593095456099'
    data['bv'] = '3230d60cc07cebcfd6e92ff220b489a3'
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_REALTIME'
    #data['typoResult'] = 'true'

    #需要使用urllib.parse.urlencode() 把data转换为需要的形式
    data = urllib.parse.urlencode(data).encode('utf-8')

    #req=urllib.request.Request(url,data,head)
    req=urllib.request.Request(url,data)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36')
     
    response = urllib.request.urlopen(req)
    html = response.read().decode('utf-8')
     
    target = json.loads(html)
     
    print('翻译结果:%s' %(target['translateResult'][0][0]['tgt']))
    time.sleep(5)

你可能感兴趣的:(python基础学习)