仍以有道翻译为例:
以下是urllib的post请求:(具体见爬虫笔记4)
import urllib.request
import urllib.parse
import json
# 请输入您要翻译的内容
content ='你好' #最后用input('请输入您要翻译的内容:')替代'你好'
url = 'https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
# 携带数据
data = {
'i': content,
'from': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '15880623642174',
'sign': 'c6c2e897040e6cbde00cd04589e71d4e',
'ts': '1588062364217',
'bv': '42160534cfa82a6884077598362bbc9d',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION'
}
data = urllib.parse.urlencode(data) #content有可能是中文
#print(type(data))
data = bytes(data,'utf-8')
req = urllib.request.Request(url,data=data,headers=headers)
res = urllib.request.urlopen(req)
html = res.read().decode('utf-8')
#print(html)
#print(type(html))
# json类型的str --> python类型的字典
r_dict = json.loads(html)
#print(type(r_dict),r_dict)
r = r_dict['translateResult']
result = r[0][0]['tgt']
print(result)
与之对比的是:
requests的post请求
import requests
import json
# 请输入您要翻译的内容
content = '你好'#input('请输入您要翻译的内容:')
url = 'https://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36'
}
# 携带数据
data = {
'i': content,
'from': 'AUTO',
'smartresult': 'dict',
'client': 'fanyideskweb',
'salt': '15880623642174',
'sign': 'c6c2e897040e6cbde00cd04589e71d4e',
'ts': '1588062364217',
'bv': '42160534cfa82a6884077598362bbc9d',
'doctype': 'json',
'version': '2.1',
'keyfrom': 'fanyi.web',
'action': 'FY_BY_CLICKBUTTION'
}
res = requests.post(url,data=data,headers=headers)
res.encoding = 'utf-8'
html = res.text
print(html)
结果: