服务器之家

服务器之家 > 正文

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

时间:2020-08-06 10:53     来源/作者:小熊&Gary

简介

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参数即可。
例:

?
1
2
3
4
5
6
7
8
# -*- 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) # 查看返回的内容

输出

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
“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参数,

?
1
2
3
4
5
6
7
8
9
# -*- 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) # 查看返回的内容

输出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
“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参数即可。

?
1
2
3
4
5
6
7
8
# -*- 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)

输出:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
“args”: {},
“data”: “”,
“files”: {
file”: “Hello world!”
},
“form”: {},
“headers”: {……
“Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”,
……
},
“json”: null,
……
}

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

到此这篇关于python爬虫使用requests发送post请求示例详解的文章就介绍到这了,更多相关python爬虫使用requests发送post请求内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_44388092/article/details/107764580

标签:

相关文章

热门资讯

2022年最旺的微信头像大全 微信头像2022年最新版图片
2022年最旺的微信头像大全 微信头像2022年最新版图片 2022-01-10
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国
暖暖日本高清免费中文 暖暖在线观看免费完整版韩国 2021-05-08
返回顶部