欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2020-11-25 12:28:09|栏目:Python代码|点击:

导入Python爬虫库Requests

import requests

一、发送表单数据

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

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)
{"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必须唯一)

payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)
{"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

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

将字典传递给参数json

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

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

上一篇:Python @property及getter setter原理详解

栏    目:Python代码

下一篇:详解python实现线程安全的单例模式

本文标题:使用Python爬虫库requests发送表单数据和JSON数据

本文地址:http://www.codeinn.net/misctech/26203.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有