有以下三种方法:

1.直接把字典传给requests.post()的json参数

requests.post(url=url,json =data,headers=headers)

  1. def send(token, tel):
  2. url = "https://www.baidu.com"
  3. phone = str(base64.b64encode(tel.encode('utf-8')), encoding="utf-8")
  4. headers = {
  5. "User-Agent": "XXX",
  6. "token": token,
  7. "content-type": "application/json",
  8. "accept-encoding": "gzip"
  9. }
  10. data = {
  11. "phone": phone
  12. }
  13. # 直接把字典传给 requests.post() 的 json 参数
  14. r = requests.post(url, headers=headers, json=data)
  15. print("{}:{}".format(tel, r.text))

2.把data进行json编码,再发送

代码如下:

  1. # 利用json对字典序列化
  2. 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 为例,代码如下:

  1. url = 'http://httpbin.org/post'
  2. files = {'file': open('upload.txt', 'rb')}
  3. r = requests.post(url, files=files) # 文件传给 requests.post() 的 files 参数
  4. print(r.text)