首页 > python爬虫

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

时间:2020-10-21 python爬虫 查看: 927

导入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爬虫库requests获取响应内容、响应状态码、响应头
下一篇:使用Python爬虫库BeautifulSoup遍历文档树并对标签进行操作详解
输入字:
相关知识
Python爬虫基础之爬虫的分类知识总结

来给大家讲python爬虫的基础啦,首先我们从爬虫的分类开始讲起,下文有非常详细的知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下

Python爬虫基础讲解之请求

今天带大家了解一下python爬虫的基础知识,文中有非常详细的解释说明,对正在学习python爬虫的小伙伴们有很好地帮助,需要的朋友可以参考下

PyQt5爬取12306车票信息程序的实现

12306是学习爬虫的比较好的一个练手网站。本文主要实现了PyQt5爬取12306车票信息程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python爬虫之m3u8文件里提取小视频的正确姿势

本文给大家分享如何正确提取m3u8文件里的.ts视频,并合成完整的.mp4格式视频,通过图文实例代码的形式给大家介绍的非常详细,对Python提取m3u8文件小视频感兴趣的朋友一起看看吧