Python中post提交数据格式攻略

爬虫除了经常用到的get请求以外,还会用到post请求,

公司里新来了几个爬虫,感觉他们对post提交的格式问题,

不是特别清楚。

关于post提交,我们经常见到的就是在html网页中使用,

经常遇到两种格式

1  表单

2  json提交

1 (表单提交)

我们可以打开google浏览器访问一个网页看一下Headers

其中  Request Method:Post

表示接受的请求为post请求

然后我们还要知道需要post什么格式

我们找到 Requests Headers(请求头)

其中有个参数是:

Content-Type:application/x-www-form-urlencoded; charset=UTF-8

Content-Type,表示提交的数据格式类型,

很明显是个表单(x-www-form-urlencoded表示是个表单数据)

那么我们就需要提交表单类型,

使用requests提交代码如下:

headers = {'1xxx':'2xxx'}
url ='3xxx'
form_data = [
            ('account', '4xxxx'),
            ('password', '5xxxx'),
             ]
requests.post(url, headers=headers, data=form_data)

2 (json提交)

依旧找到 Requests Headers(请求头)

发现此时的Content-Type后面的值变成了 application/json

很明显,此时需要提交json格式数据

headers = {'1xxx':'2xxx'}
url ='3xxx'
pre = {"username": "4xxx", "password": "5xxx"}
requests.post(url, headers=headers, data=json.dumps(pre))

提醒:提交什么格式数据主要看Requests Headers(请求头)中的Content-Type中是什么参数

猜你喜欢

转载自blog.csdn.net/m0_38124502/article/details/81676216
今日推荐