在Python 3中,对`urllib`和`urllib2`库进行了重大重构,以提供更清晰的模块化设计和更好的功能分离。这使得开发者能够更方便地处理网络请求和响应,同时也提高了代码的可读性和可维护性。下面我们将详细探讨这些变化及其用法。 1. **模块拆分**: 在Python 2中,`urllib`和`urllib2`是两个主要的模块,分别用于处理URL操作和HTTP请求。而在Python 3中,这两个模块被拆分为以下几个子模块: - `urllib.request`:负责发出HTTP、HTTPS等请求,包含了`urlopen()`和`Request()`等函数,类似于Python 2中的`urllib2`。 - `urllib.parse`:用于URL解析和重组,包括`urljoin()`、`urlsplit()`等函数,取代了Python 2中的`urlparse`模块。 - `urllib.error`:处理与请求相关的异常,如`HTTPError`和`URLError`。 - `urllib.response`:处理HTTP响应,虽然不常直接使用,但它是处理响应数据的重要组成部分。 2. **API更改**: - `urllib2.urlopen()`:在Python 3中,这个函数被移动到了`urllib.request`模块,新的调用方式为`urllib.request.urlopen()`。 - `urllib2.Request()`:同样,现在在`urllib.request`中,使用`urllib.request.Request()`来创建请求对象。 3. **HTTP头处理**: 在Python 3中,添加HTTP头可以通过`Request`对象的`add_header()`方法,如示例代码所示,可以模拟浏览器发送请求。 4. **Cookie处理**: Python 2中的`cookielib`模块在Python 3中改名为`http.cookiejar`。要处理Cookie,可以创建一个`CookieJar`对象,并将其添加到`HTTPCookieProcessor`中,然后构建一个`opener`来处理带有Cookie的请求。 示例代码展示了如何使用Python 3的新`urllib`库进行网络请求: ```python import urllib.request import http.cookiejar url = "http://www.baidu.com" # 第一种方法:简单的GET请求 response1 = urllib.request.urlopen(url) print('状态码:', response1.getcode()) print('内容长度:', len(response1.read())) # 第二种方法:添加HTTP头 request = urllib.request.Request(url) request.add_header("User-Agent", "Mozilla/5.0") response2 = urllib.request.urlopen(request) print('状态码:', response2.getcode()) print('内容长度:', len(response2.read())) # 第三种方法:处理Cookie cj = http.cookiejar.CookieJar() opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) urllib.request.install_opener(opener) response3 = urllib.request.urlopen(url) print('状态码:', response1.getcode()) print('Cookie:', cj) # 输出Cookie print('内容:', response1.read()) ``` Python 3的`urllib`库提供了更加完善的网络请求功能,不仅包含基本的GET和POST请求,还能处理Cookie、HTTP头等复杂情况。这种重构让开发者能够更灵活地处理网络请求,同时保持代码的简洁和清晰。了解并掌握这些变化对于进行Python 3的网络编程至关重要。






















