有以下三种方法:
1.直接把字典传给requests.post()的json参数
requests.post(url=url,json =data,headers=headers)
def send(token, tel):
url = "https://www.baidu.com"
phone = str(base64.b64encode(tel.encode('utf-8')), encoding="utf-8")
headers = {
"User-Agent": "XXX",
"token": token,
"content-type": "application/json",
"accept-encoding": "gzip"
}
data = {
"phone": phone
}
# 直接把字典传给 requests.post() 的 json 参数
r = requests.post(url, headers=headers, json=data)
print("{}:{}".format(tel, r.text))
2.把data进行json编码,再发送
代码如下:
# 利用json对字典序列化
r = requests.post(url=url,data=json.dumps(data),headers=headers)
3.上传文件
“Content-Type”: “application/x-www-form-urlencoded”
上传文件在爬虫中使用的很少,不过还是使用requests讲解一下使用方式。Content-Type类型为multipart/form-data,以multipart形式发送post请求,只需将一文件传给 requests.post() 的files参数即可。还是以 http://httpbin.org/post 为例,代码如下:
url = 'http://httpbin.org/post'
files = {'file': open('upload.txt', 'rb')}
r = requests.post(url, files=files) # 文件传给 requests.post() 的 files 参数
print(r.text)