温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python爬虫中Requests实现post请求的案例

发布时间:2020-11-12 09:38:34 来源:亿速云 阅读:444 作者:小新 栏目:编程语言

这篇文章主要介绍Python爬虫中Requests实现post请求的案例,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

对于 POST 请求来说,我们一般需要为它增加一些参数。那么最基本的传参方法可以利用 data 这个参数。

import requests   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",     "Content-Length": "23",     "Content-Type": "application/x-www-form-urlencoded",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.9.1"   },   "json": null,   "url": "http://httpbin.org/post" }

可以看到参数传成功了,然后服务器返回了我们传的数据。 有时候我们需要传送的信息不是表单形式的,需要我们传 JSON 格式的数据过去,所以我们可以用 json.dumps () 方法把表单数据序列化。

import json import requests   url = 'http://httpbin.org/post' payload = {'some': 'data'} r = requests.post(url, data=json.dumps(payload)) print r.text

运行结果

{   "args": {},   "data": "{\"some\": \"data\"}",   "files": {},   "form": {},   "headers": {     "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Content-Length": "16",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.9.1"   },   "json": {     "some": "data"   },     "url": "http://httpbin.org/post" }

通过上述方法,我们可以 POST JSON 格式的数据 如果想要上传文件,那么直接用 file 参数即可 新建一个 a.txt 的文件,内容写上 Hello World!

import requests   url = 'http://httpbin.org/post' files = {'file': open('test.txt', 'rb')} r = requests.post(url, files=files) print r.text

可以看到运行结果如下

{   "args": {},   "data": "",   "files": {     "file": "Hello World!"   },   "form": {},   "headers": {     "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Content-Length": "156",     "Content-Type": "multipart/form-data; boundary=7d8eb5ff99a04c11bb3e862ce78d7000",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.9.1"   },   "json": null,   "url": "http://httpbin.org/post" }

这样我们便成功完成了一个文件的上传。 requests 是支持流式上传的,这允许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传,仅需为你的请求体提供一个类文件对象即可

with open('massive-body') as f: requests.post('http://some.url/streamed', data=f)

这是一个非常实用方便的功能。

以上是Python爬虫中Requests实现post请求的案例的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI