Python发送HTTP请求的常用方法有urllib、requests、http.client等。
urllib
urllib是Python内置的HTTP请求库,包含了urllib.request和urllib.error两个模块,其中urllib.request模块提供了最基本的HTTP请求操作,urllib.error模块提供了HTTP请求的异常处理。
使用urllib发送HTTP请求的基本步骤如下:
- 创建一个Request对象,用来描述一个HTTP请求;
- 使用urllib.request.urlopen()函数发送请求;
- 处理服务器返回的结果。
import urllib.request # 创建一个Request对象 request = urllib.request.Request("http://www.example.com/") # 发送请求 response = urllib.request.urlopen(request) # 处理结果 print(response.read().decode('utf-8'))
requests
requests是Python中最流行的HTTP请求库,它比urllib更加简单易用,支持多种HTTP请求方法,支持SSL、Cookies等功能,还可以接收和发送JSON数据,支持流式上传和下载。
使用requests发送HTTP请求的基本步骤如下:
- 导入requests模块;
- 使用requests.get()函数发送请求;
- 处理服务器返回的结果。
import requests # 发送请求 response = requests.get("http://www.example.com/") # 处理结果 print(response.text)
http.client
http.client是Python内置的HTTP客户端库,提供了HTTPConnection和HTTPSConnection两个类,用来处理HTTP和HTTPS请求,支持普通请求和持久连接,支持Cookies等功能。
使用http.client发送HTTP请求的基本步骤如下:
- 导入http.client模块;
- 创建HTTPConnection或HTTPSConnection对象;
- 使用对象的request()方法发送请求;
- 处理服务器返回的结果。
import http.client # 创建HTTPConnection对象 conn = http.client.HTTPConnection("www.example.com") # 发送请求 conn.request("GET", "/") # 处理结果 response = conn.getresponse() print(response.read().decode('utf-8'))
以上三种方法都可以用来发送HTTP请求,在实际开发中,可以根据需要选择合适的方法。