python爬虫:模拟有道词典翻译文本

python爬虫:模拟有道词典翻译文本

引言

初步学习爬虫,写一个关于模拟有道词典翻译文本的脚本

代码

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)

运行结果

python爬虫:模拟有道词典翻译文本

总结

继续努力!!!

上一篇:第八课:urllib库基本使用-(崔庆才_Python3爬虫入门到精通课程视频 34课)总结


下一篇:Python网络编程相关的库与爬虫基础