1. 程式人生 > >Python爬取有道字典出現錯誤 {‘errorcode’:50}

Python爬取有道字典出現錯誤 {‘errorcode’:50}

import urllib.request
import urllib.parse
import json
content = input("請輸入帶翻譯的內容: ")
url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
data = {}
data['i']=content
data['from']='AUTO'
data['to']='AUTO'
data['smartresult']= 'dict'
data['client']= 'fanyideskweb'
data['salt']='1535438497358'
data['sign']= 'f19e9cbeddb439ff1fcf17265010373e'
data['doctype']= 'json'
data['version']= '2.1'
data['keyfrom']= 'fanyi.web'
data['action']='FY_BY_CLICKBUTTION'
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)
target = target['translateResult'][0][0]['tgt']
print(target)
出現的錯誤是:

請輸入帶翻譯的內容: i
Traceback (most recent call last):
  File "E:\python課後題\54-1.py", line 26, in <module>
    target = target['translateResult'][0][0]['tgt']
KeyError: 'translateResult'

將在審查元素中獲得的url中translate後面的_o去掉,錯誤就消失