系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > 脚本中心 > python > 详细页面

使用Python爬虫库requests发送表单数据和JSON数据

时间:2020-01-27来源:电脑系统城作者:电脑系统城

导入Python爬虫库Requests


 
  1. import requests

 

一、发送表单数据

要发送表单数据,只需要将一个字典传递给参数data


 
  1. payload = {'key1': 'value1', 'key2': 'value2'}
  2. r = requests.post("http://httpbin.org/post", data=payload)
  3. print(r.text)

 
  1. {"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.14.2"},"json":null,"origin":"110.18.198.88","url":"http://httpbin.org/post"}

也可以将一个元组列表传递给参数data,这样可以实现多个value对应一个key的情况(字典的key必须唯一)


 
  1. payload = (('key1', 'value1'), ('key1', 'value2'))
  2. r = requests.post('http://httpbin.org/post', data=payload)
  3. print(r.text)

 
  1. {"args":{},"data":"","files":{},"form":{"key1":["value1","value2"]},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.14.2"},"json":null,"origin":"110.18.198.88","url":"http://httpbin.org/post"}

二、发送字符串(JSON)数据

将json字符串传递给参数data


 
  1. import json
  2. url = 'https://api.github.com/some/endpoint'
  3. payload = {'some': 'data'}
  4. r = requests.post(url, data=json.dumps(payload))

将字典传递给参数json


 
  1. url = 'https://api.github.com/some/endpoint'
  2. payload = {'some': 'data'}
  3. r = requests.post(url,json=payload)

更多关于Python爬虫库requests的使用方法请查看下面的相关链接

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载