Python crawler: Simulate Youdao dictionary translation text

Python crawler: Simulate Youdao dictionary translation text

introduction

Preliminary learning of reptiles, writing a script about simulating Youdao dictionary translation text

the code

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


while True:   
    content  =  input("请输入你想翻译的内容:")
    if content == 'q':
        braek
        
    #url中带—_o会导致{
    
    "errorCode":50}
    #url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    #获取浏览器类型的'User-Agent信息,避免禁止访问错误
    head = {
    
    }
    head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.1071 SLBChan/1'

    data = {
    
     }
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] =  'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = '16137170355211'
    data['sign'] = '37d618ef49272a7dd5325e8a375b261b'
    data['lts'] = '1613717035521'
    data['bv'] = '8ec2482c48c5d4cf3ff41e80cd83571b'
    data['doctype'] =  'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_REALTlME'

    data = urllib.parse.urlencode(data).encode('utf-8')

    #实例化对象
    req = urllib.request.Request(url,data,head)
    response = urllib.request.urlopen(req)

    html = response.read().decode('utf-8')
    html_1 = json.loads(html)['translateResult'][0][0]['tgt']


    print("翻译结果—》" + html_1)

    time.sleep(2)

operation result

insert image description here

Summarize

keep it up! ! !

Guess you like

Origin blog.csdn.net/MZYYZT/article/details/113928666