首先说下post请求和get请求的区别
get:数据信息会在地址栏中显现
post:数据信息会在报头中出现,比较安全
例子:
该例子是在有道翻译中来实现的,实现翻译数据
import urllib
import urllib.parse
import urllib.request
#抓包的url地址,并不是浏览器上显示的url
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
#完整的headers
headers = {
"X-Requested-With": "XMLHttpRequest",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Accept-Language": "zh-CN,zh;q=0.9"
}
key = input("请输入你想要翻译的数据:")
print(key)
#发送到web服务器的表单数据
form_data = {
"i": key,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": "1532253411766",
"sign": "f045436c907304b304285bb3b28a81fc",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action": "FY_BY_REALTIME",
"typoResult": "false"
}
#将数据进行转码
data = urllib.parse.urlencode(form_data).encode(encoding='UTF8')
#构建一个请求对象
request = urllib.request.Request(url,data = data,headers = headers)
#回应
response = urllib.request.urlopen(request)
print(response.read())
结果:
C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\python.exe E:/untitled/Python_Test/Post_Test.py
请输入你想要翻译的数据:hello
hello
b' {"type":"EN2ZH_CN","errorCode":0,"elapsedTime":1,"translateResult":[[{"src":"hello","tgt":"\xe4\xbd\xa0\xe5\xa5\xbd"}]]}\n'Process finished with exit code 0
注意:在结果中有"type":"EN2ZH_CN",该字段是指翻译只能将英文翻译为中文,不能将中文翻译成英文。
问题1:
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.
出现以上错误,说明是转码的问题,因此在python中需要将数据进行转码。
data = urllib.parse.urlencode(form_data)
因此将上句改为:
data = urllib.parse.urlencode(form_data).encode(encoding="UTF8")
问题2:
C:\Users\DELL\AppData\Local\Programs\Python\Python36-32\python.exe E:/untitled/Python_Test/Post_Test.py
请输入你想要翻译的数据:hello
hello
b'{"errorCode":50}'Process finished with exit code 0
把url = "http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"的“_o”删掉就行
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"