好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

爬虫使用requests发送post请求示例

  简介

  HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括:

  application/x-www-form-urlencoded 最常见post提交数据的方式,以form表单形式提交数据。

  application/json 以json串提交数据。

  multipart/form-data 一般使用来上传文件。

  一、 以form表单发送post请求

  Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。

  例:

  # -*- coding: utf-8 -*-

  # author:Gary

  import requests

  url = 'http://httpbin.org/post' # 一个测试网站的url

  data = {'key1': 'value1', 'key2': 'value2'} # 你发送给这个的数据

  r = requests.post(url, data=data) # 使用requests的post方法,data接受你想发送的数据

  print(r.text) # 查看返回的内容

  输出

  {

  “args”: {},

  “data”: “”,

  “files”: {},

  #你提交的表单数据

  “form”: {

  “key1”: “value1”,

  “key2”: “value2”

  },

  “headers”: {

  ……

  “Content-Type”: “application/x-www-form-urlencoded”,

  ……

  },

  “json”: null,

  ……

  }

  可以看到,请求头中的Content-Type字段已设置为application/x-www-form-urlencoded,且data = {‘key1’: ‘value1’, ‘key2’: ‘value2’}以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据。

  二、 以json形式发送post请求

  可以将一json串传给requests.post()的data参数,

  # -*- coding: utf-8 -*-

  # author:Gary

  import requests

  import json

  url = 'http://httpbin.org/post' # 一个测试网站的url

  json_data = json.dumps({'key1': 'value1', 'key2': 'value2'}) # 你发送给这个的数据,数据格式转为json

  r = requests.post(url, data=json_data) # 使用requests的post方法,data接受你想发送的数据

  print(r.text) # 查看返回的内容

  输出:郑州看胎记哪个医院好 http://HdhCmsTestzykdbh测试数据/

  {

  “args”: {},

  “data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,

  “files”: {},

  “form”: {},

  “headers”: {

  ……

  “Content-Type”: “application/json”,

  ……

  },

  “json”: {

  “key1”: “value1”,

  “key2”: “value2”

  },

  ……

  }

  可以看到,请求头的Content-Type设置为application/json,并将json_data这个json串提交到服务端中。

  三、 以multipart形式发送post请求(上传文件)

  Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可。

  # -*- coding: utf-8 -*-

  # author:Gary

  import requests

  url = 'http://httpbin.org/post'

  files = {'file': open('report.txt', 'rb')} # 目录下得有report.txt文件才能上传,rb是指以二进制格式打开一个文件用于只读。

  r = requests.post(url, files=files) # 通过files参数指定你想发送的文件的内容

  print(r.text)

  输出:

  {

  “args”: {},

  “data”: “”,

  “files”: {

  “file”: “Hello world!”

  },

  “form”: {},

  “headers”: {……

  “Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”,

  ……

  },

  “json”: null,

  ……

  }

  文本文件report.txt的内容只有一行:Hello world!,从请求的响应结果可以看到数据已上传到服务端中。

查看更多关于爬虫使用requests发送post请求示例的详细内容...

  阅读:20次