1.通过Request的headers参数修改
1 import urllib.request 2 import urllib.parse 3 import json 4 5 content = input("请输入翻译的内容:") 6 7 url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule' 8 9 head = {} 10 head['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36' 11 data = {} 12 13 data['i'] = content 14 15 data['from'] = 'en' 16 data['to'] = 'zh-CHS' 17 data['smartresult'] = 'dict' 18 data['client'] = 'fanyideskweb' 19 data['salt'] = '15934837793668' 20 data['sign'] = '6c263b05b4511c7c9fc9e540d8cb3b42' 21 data['ts'] = '1593483779366' 22 data['bv'] = 'dd0840fad0d96c2e9de5a4f181a39d98' 23 data['doctype'] = 'json' 24 data['version'] = '2.1' 25 data['keyfrom'] = 'fanyi.web' 26 data['action'] = 'FY_BY_CLICKBUTTION' 27 data = urllib.parse.urlencode(data).encode('utf-8') 28 29 req = urllib.request.Request(url,data,head) 30 response = urllib.request.urlopen(req) 31 32 html =response.read().decode('utf-8') 33 34 target = json.loads(html) 35 print("翻译的结果是:%s" %(target['translateResult'][0][0]['tgt']))
运行结果
输入翻译的内容:love 翻译的结果是:爱 >>> req.headers {'User-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'}
2.通过Request.add_header()方法修改
附加代码
import urllib.request import urllib.parse import json content = input("请输入翻译的内容:") url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule' #head = {} #head['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36' data = {} data['i'] = content data['from'] = 'en' data['to'] = 'zh-CHS' data['smartresult'] = 'dict' data['client'] = 'fanyideskweb' data['salt'] = '15934837793668' data['sign'] = '6c263b05b4511c7c9fc9e540d8cb3b42' data['ts'] = '1593483779366' data['bv'] = 'dd0840fad0d96c2e9de5a4f181a39d98' data['doctype'] = 'json' data['version'] = '2.1' data['keyfrom'] = 'fanyi.web' data['action'] = 'FY_BY_CLICKBUTTION' data = urllib.parse.urlencode(data).encode('utf-8') req = urllib.request.Request(url,data) req.add_header('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36') response = urllib.request.urlopen(req) html =response.read().decode('utf-8') target = json.loads(html) print("翻译的结果是:%s" %(target['translateResult'][0][0]['tgt']))