网站首页 > 技术文章 正文
使用 python urllib 模块发出 Web 请求。
urllib模块是内置于Python标准库中的标准模块,允许用户使用URL(统一资源定位器)。可以用它做很多简洁的事情,例如访问API资源,发出不同类型的HTTP请求,如GET,POST,PUT,DELETE等。
如何使用 urllib 模块来访问 API 资源。使用 JsonPlaceholder进行虚拟的 REST API 调用,这是一个非常简洁的工具。
import urllib.request
向 google.com 提出请求,看看得到了什么。
import urllib.request
with urllib.request.urlopen("https://www.google.com/") as url:
print(url.read(300))
在这里,使用了一个上下文管理器,它可以优雅地处理 url 的打开和关闭。urlopen() 函数返回一个字节对象,打印它的前 300 个字节。
b'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="j2RUvuN1fVmpA'
[Finished in 7.3s]
如果知道字节对象的编码,可以打印字符串结果。在上述输出的元标记中可以清楚地看到编码是utf-8。
import urllib.request
with urllib.request.urlopen("https://www.google.com/") as url:
print(url.read(300).decode("utf-8"))
上面的代码现在将一个 utf-8 解码字节对象作为字符串返回,如果我们需要对它做一些事情,可以稍后解析它。
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="MnpsG49CZsHqd
[Finished in 2.0s]
获取请求。
GET 请求用于从 URL 终结点检索特定资源。让向 JsonPlaceholder API 发出一个 GET 请求来获取一些待办事项。
import urllib.request
req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1')
with urllib.request.urlopen(req) as resp:
print(resp.read().decode('utf-8'))
在这里,将 url 参数传递给 urllib.request 上定义的 Request 方法。读取响应对象并对其进行解码。如果仔细检查代码,由于我们不指定任何数据参数(这基本上意味着它是 None),因此该方法默认为 GET。
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
[Finished in 4.5s]
这里的输出实际上看起来像一个带有键值对的 python 字典,但现实是它只是一个字符串。可以通过将解码的响应对象包装在 type() 中来验证它,并查看其类型为 string。
如果需要访问此响应对象的各种键值对,需要使用 json.loads() 方法解析它,需要 json 模块
import json
import urllib.request
# We can now control the number of todos we want to be returned.
num_of_todos = 1
req = urllib.request.Request(url=f'https://jsonplaceholder.typicode.com/todos/{num_of_todos}')
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read().decode("utf-8"))
print(data)
print(type(data))
print(data["title"])
现在返回的数据确实是一个python字典,可以像往常一样访问键值对。
{'userId': 1, 'id': 1, 'title': 'delectus aut autem', 'completed': False}
<class 'dict'>
delectus aut autem
[Finished in 1.7s]
开机自检请求。
将一些数据发送到服务器以创建或更新资源时,使用 POST 方法。
import json
import urllib.request
# This is our Todo
data = {
"userId": 101,
"id": 100,
"title": "This is a POST request",
"completed": True
}
# Dump the todo object as a json string
data = json.dumps(data)
req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/', data = bytes(data.encode("utf-8")), method = "POST")
# Add the appropriate header.
req.add_header("Content-type", "application/json; charset=UTF-8")
with urllib.request.urlopen(req) as resp:
response_data = json.loads(resp.read().decode("utf-8"))
print(response_data)
一个包含必要键值对的 python 字典。将其转储为 JSON 字符串。将数据作为字节对象传递给 Request 方法的数据参数。 将 Content-type 标头添加为 application/json,这表示希望发布的数据是 JSON 对象。读取和解码响应对象并打印它。
{'userId': 101, 'id': 201, 'title': 'This is a POST request', 'completed': True}
[Finished in 2.0s]
放置请求。
需要修改服务器上的某个资源, 使用 PUT 请求。
import json
import urllib.request
# This is our Todo
data = {
"userId": 1,
"id": 1,
"title": "This is a PUT request",
"completed": False
}
# Dump the todo object as a json string
data = json.dumps(data)
req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1', data = bytes(data.encode("utf-8")), method = "PUT")
# Add the appropriate header.
req.add_header("Content-type", "application/json; charset=UTF-8")
with urllib.request.urlopen(req) as resp:
response_data = json.loads(resp.read().decode("utf-8"))
print(response_data)
大部分代码保持不变。唯一的区别是 将方法指定为 PUT
{'userId': 1, 'id': 1, 'title': 'This is a PUT request', 'completed': False}
[Finished in 2.0s]
删除请求
删除服务器上的特定资源, 使用 DELETE 请求。
import json
import urllib.request
req = urllib.request.Request(url = 'https://jsonplaceholder.typicode.com/todos/1', method = "DELETE")
with urllib.request.urlopen(req) as resp:
response_data = json.loads(resp.read().decode("utf-8"))
print(response_data)
只需将方法指定为 DELETE 要删除的待办事项(即 /todos/1)。
{}
[Finished in 2.6s]
响应是一个空对象, 已经成功删除了待办事项。
猜你喜欢
- 2024-10-03 python模块之aioHttp 异步请求(在crm中,哪个模块用于跟踪和管理客户服务请求)
- 2024-10-03 推荐几个最佳python应用服务器(一起学习吧)
- 2024-10-03 让 HTTP 服务人类——Python Requests 模块基本用法总结
- 2024-10-03 关于爬虫,HTTP协议了解一下!(关于爬虫,http协议了解一下!正确的有)
- 2024-10-03 「Python」在HTTP请求使用长连接(keep-alive)提高传输效率
- 2024-10-03 干货分享丨Python的HTTP库及示例(http//www.python.org/downloads)
- 2024-10-03 微软太良心了,提供免费服务器可以搭建Python网站
- 2024-10-03 python爬虫必备库——requests(python爬虫需要的库)
- 2024-10-03 如何用Python语言开发大型服务器程序
- 2024-10-03 使用Python获取HTTP请求头数据(在python中用于获取用户输入的函数是)
- 10-02基于深度学习的铸件缺陷检测_如何控制和检测铸件缺陷?有缺陷铸件如何处置?
- 10-02Linux Mint 22.1 Cinnamon Edition 搭建深度学习环境
- 10-02AWD-LSTM语言模型是如何实现的_lstm语言模型
- 10-02NVIDIA Jetson Nano 2GB 系列文章(53):TAO模型训练工具简介
- 10-02使用ONNX和Torchscript加快推理速度的测试
- 10-02tensorflow GPU环境安装踩坑日记_tensorflow配置gpu环境
- 10-02Keye-VL-1.5-8B 快手 Keye-VL— 腾讯云两卡 32GB GPU保姆级部署指南
- 10-02Gateway_gateways
- 最近发表
-
- 基于深度学习的铸件缺陷检测_如何控制和检测铸件缺陷?有缺陷铸件如何处置?
- Linux Mint 22.1 Cinnamon Edition 搭建深度学习环境
- AWD-LSTM语言模型是如何实现的_lstm语言模型
- NVIDIA Jetson Nano 2GB 系列文章(53):TAO模型训练工具简介
- 使用ONNX和Torchscript加快推理速度的测试
- tensorflow GPU环境安装踩坑日记_tensorflow配置gpu环境
- Keye-VL-1.5-8B 快手 Keye-VL— 腾讯云两卡 32GB GPU保姆级部署指南
- Gateway_gateways
- Coze开源本地部署教程_开源canopen
- 扣子开源本地部署教程 丨Coze智能体小白喂饭级指南
- 标签列表
-
- cmd/c (90)
- c++中::是什么意思 (84)
- 标签用于 (71)
- 主键只能有一个吗 (77)
- c#console.writeline不显示 (95)
- pythoncase语句 (88)
- es6includes (74)
- sqlset (76)
- apt-getinstall-y (100)
- node_modules怎么生成 (87)
- chromepost (71)
- flexdirection (73)
- c++int转char (80)
- mysqlany_value (79)
- static函数和普通函数 (84)
- el-date-picker开始日期早于结束日期 (76)
- js判断是否是json字符串 (75)
- c语言min函数头文件 (77)
- asynccallback (87)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- java (73)
- js数组插入 (83)
- mac安装java (72)
- 无效的列索引 (74)