import urllib.request import urllib.parse import json while True: content = input('請輸入需要翻譯的內容(退出輸入Q):') if content == 'Q': break else: url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=http://www.youdao.com/' data = {} data['type'] = 'AUTO' data['i'] = content data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' 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'][0][0]['tgt'])
程序執行情況:
這里要注意的是兩個函數urllib.request.urlopen()與urllib.parse.urlencode()。
urllib.request.urlopen()其實不止一個參數,有好幾個哦,其中第二個是data,data應該是一個buffer的標准應用程序/ x-www-form-urlencoded格式(python標准庫原文:data should be a buffer in the standard application/x-www-form-urlencoded format)。urllib.parse.urlencode()函數接受一個映射或序列集合,並返回一個字符串的格式(python標准庫原文:The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format)。我們可以看看urllib.parse.urlencode()的結果是什么樣的:
上圖的結果剛好與urllib.request.urlopen()的data參數的數據類型要求一致了。
注意,上面urlopen當中的url,這個是分析有道翻譯頁面的真實的Request URL: