◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。
http 是一种基于 tcp/ip 的应用层通信协议,它标准化了客户端和服务器之间的通信方式。
它用于使用超文本链接加载网页。
“无论您是从 api 获取数据还是提交表单数据,python 中的 requests 库都是您的首选工具,可以让 http 请求无缝且直观。”
在终端中输入:
pip install requests
它是 python 标准库生态系统的一部分,但需要安装。
import requests response = requests.get('https://jsonplaceholder.typicode.com/todos') print(response.json())
响应对象包含请求的所有详细信息,包括状态代码、标头和数据。使用response.json()直接解析json数据。
如果您使用请求库,该库支持多种请求:
data = {'title': 'create an example', 'completed': 'true', 'userid': 1} response = requests.post('https://jsonplaceholder.typicode.com/todos',json=data) print(response.json())
response = requests.get('https://jsonplaceholder.typicode.com/todos') if response.status_code == 200: print("success:", response.text) else: print("failed with status code:", response.status_code)
files = {'file': open('firstexample.txt', 'rb')} response = requests.post('https://jsonplaceholder.typicode.com/todos', files=files) print(response.status_code)
这些是一些可以使用请求库的实际应用程序:
立即学习“Python免费学习笔记(深入)”;
掌握 python 的 requests 库是使用 api 或 web 服务的开发人员的一项基本技能。它简化了复杂的 http 操作,让您更轻松地专注于应用程序的逻辑。
更多信息请参考官方文档。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。