Python 官方文档:入门教程 => 点击学习
目录1、简单使用2、构建请求查询参数3、构建请求头Headers4、构建POST请求数据 4.1 表单数据4.2 JSON数据5、获取响应内容6、Cookies7、超时配置8、代理r
requests
库实现了Http协议中绝大部分功能,提供了Keep-Alive
、连接池、Cookie
持久化、HTTP(S)代理支持、连接超时等很多功能特性,最重要的是它同时支持python2
和ython3,而且能在PyPy下完美运行。
使用前需要使用pip install requests
命令进行安装。
res = requests.get("http://httpbin.org/get")
# 状态码
print(res.status_code)
# 响应头
print(res.headers["Content-Type"], res.headers["Server"])
# 响应内容
print(res.text)
执行结果如下:
200
application/json gunicorn/19.9.0
{
"args": {},
"headers": {
"Accept": "**",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-fORM-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-requests/2.26.0",
"X-Amzn-Trace-Id": "Root=1-614d7d91-559333ee19237f845026ef37"
},
"json": null,
"origin": "xxx.xxx.xx.xx",
"url": "http://httpbin.org/post"
}
import json
import requests
url = "http://httpbin.org/post"
data = {"key": "value"}
data = json.dumps(data)
res = requests.post(url, data=data)
print(res.text)
运行结果如下:
{
"args": {},
"data": "{\"key\": \"value\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "16",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.26.0",
"X-Amzn-Trace-Id": "Root=1-614d7e91-065887f925dce94d6d03b2e4"
},
"json": {
"key": "value"
},
"origin": "xxx.xxx.xx.xx",
"url": "http://httpbin.org/post"
}
使用requests
请求处理响应体也非常方便灵活,可以使用的属性有content
、text
、json()
。
content
属性获取的是byte
类型的数据。
import requests
res = requests.get("http://httpbin.org/get")
print(res.content)
text属性获取的是str类型的数据。
import requests
res = requests.get("http://httpbin.org/get")
print(res.text)
如果返回的内容是json
格式的数据时,就可以使用json()方法返回一个经过json.loads()处理后的对象。
import requests
url = "http://httpbin.org/post"
res = requests.post(url)
print(res.json())
如果响应中包含了cookie
信息,我们可以使用cookies
属性获取。
res = requests.get("http://httpbin.org/get")
print(res.cookies)
另外还可以使用cookies
参数向服务端发送cookies
信息。
url = "http://httpbin.org/cookies"
cookies = {"cookies": "xxxxx"}
r = requests.get(url, cookies=cookies)
print(r.text)
可以利用timeout
参数来配置最大请求时间。
如果需要使用代理,我们可以通过proxies
参数来配置。
import requests
proxies = {
'http': 'http://175.7.199.202:3256',
'https': 'http://175.7.199.59:3256',
}
requests.get('http://httpbin.org/get', proxies=proxies)
总结:
到此这篇关于Python HTTP库 requests 的简单使用详情的文章就介绍到这了,更多相关Python HTTP库 requests 的简单使用内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python HTTP库 requests 的简单使用详情
本文链接: https://www.lsjlt.com/news/137125.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0