使用 Python 编程实现 GET 和 POST 请求

pythonserver side programmingprogramming更新于 2025/7/31 17:16:17

Python 可用于访问网页以及将内容发布到网页。有各种模块,如 httplib、urllib、httplib2 等,但请求模块最简单,可用于编写涉及 GET 和 POST 方法的更简单但功能强大的程序。

GET 方法

GET 方法是 Python 请求模块的一部分,用于从 Web URL 获取数据。在下面的示例中,我们访问自己的网站并通过 get 方法找出各种响应。我们获取了编码、响应时间以及标头和正文部分。

示例

import 请求

req = request.get('http://www.tutorialspoint.com/')

# 页面编码
e = req.encoding
print("Encoding: ",e)

# 响应代码
s = req.status_code
print("Response code: ",s)

# 响应时间
t = req.elapsed
print("Response Time: ",t)


t = req.headers['Content-Type']
print("Header: ",t)

z = req.text
print("\nSome text from the web page:\n",z[0:200])

输出

运行上述代码得到以下结果 −

Encoding: UTF-8
Response code: 200
Response Time: 0:00:00.103850
Header: text/html; charset=UTF-8

Some text from the web page:

POST 方法

POST 方法主要用于通过表单将数据发送到服务器,以在服务器中创建或更新数据。requests 模块为我们提供了 post 方法,该方法可以通过获取 URL 和数据参数的值直接发送数据。

在下面的示例中,我们通过 post 方法将一些数据发布到 httpbin.org 网站,并获取有关如何发布的响应。

示例

import requests
in_values = {'username':'Jack','password':'Hello'}
res = requests.post('https://httpbin.org/post',data = in_values)
print(res.text)

输出

运行上述代码得到以下结果 −

{
"args": {},
"data": "",
"files": {},
"form": {
"password": "Hello",
"username": "Jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "28",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5ef75488-969f97a68bb72642b97b6d50"
},
"json": null,
"origin": "122.xxx.yy.zzz",
"url": "https://httpbin.org/post"
}

相关文章


有用资源