snail:) 发表于 2018-2-23 23:45:07

用requests访问有道翻译(方便日后回来查阅)

本帖最后由 snail:) 于 2018-2-23 23:48 编辑

import requests

while 1:
   
    content = input("请输入需要翻译的内容[按‘q’结束]:")
    if content == 'q':
      print('欢迎下次使用!')
      break
    else:

      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'] = '1519180629227'
      data['sign'] = 'e2261e9c5853cb410635984e41a144a0'
      data['doctype'] = 'json'
      data['version'] = '2.1'
      data['keyfrom'] = 'fanyi.web'
      data['action'] = 'FY_BY_REALTIME'
      data['typoResult'] = 'false'

      headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
      html = requests.get(url,params=data,headers=headers)
      target = html.json()
      print("翻译结果:%s" % (target['translateResult']['tgt']))



老版用urllib.request的代码如下做个比较
import urllib.request
import urllib.parse
import json

while 1:
   
    content = input("请输入需要翻译的内容[按‘q’结束]:")
    if content == 'q':
      print('欢迎下次使用!')
      break
    else:

      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'] = '1519180629227'
      data['sign'] = 'e2261e9c5853cb410635984e41a144a0'
      data['doctype'] = 'json'
      data['version'] = '2.1'
      data['keyfrom'] = 'fanyi.web'
      data['action'] = 'FY_BY_REALTIME'
      data['typoResult'] = 'false'
      data = urllib.parse.urlencode(data).encode('utf-8')

      response = urllib.request.urlopen(url, data)
      html = response.read().decode('utf-8')

      target = json.loads(html)

      print("翻译结果:%s" % (target['translateResult']['tgt']))






最后有个问题,有道翻译是POST的形式传递的,虽然requests.get()也可以传参,还是想问下有没有大佬能帮我修改下用requests.post()获取网页信息,我试了好多次都不行
页: [1]
查看完整版本: 用requests访问有道翻译(方便日后回来查阅)