Python爬虫进阶:urllib3核心功能与实战用法详解

闻溪
闻溪
发布时间:2026-10-13| 6人浏览过
原创

本文详细介绍Python库urllib3的核心特性,包括线程安全、连接池管理、SSL/TLS验证及代理支持。通过具体代码示例,演示如何使用urllib3发起GET/POST请求、处理JSON数据、上传文件、设置超时与重试机制,并解决HTTPS证书验证警告问题,帮助开发者高效构建网络请求应用。

Urllib3是一个功能强大且结构清晰的Python HTTP客户端库,目前许多Python原生系统已采用该库。相较于Python标准库中的urllib,urllib3提供了多项重要增强特性:

  1. 线程安全
  2. 连接池管理
  3. 客户端SSL/TLS证书验证
  4. 支持文件分块编码上传
  5. 自动处理重复请求及HTTP重定向
  6. 支持压缩编码解码
  7. 支持HTTP和SOCKS代理配置

一、GET请求实现

urllib3主要依赖连接池对象来执行网络请求,因此在发起访问前,必须首先创建一个连接池实例。具体代码如下:

import urllib3

url = "http://httpbin.org"
http = urllib3.PoolManager();
r = http.request('GET',url+"/get")
print(r.data.decode())
print(r.status)

带参数的get
r = http.request('get','http://www.baidu.com/s',fields={'wd':'周杰伦'})
print(r.data.decode())

通过查看源码可知:

def request(self, method, url, fields=None, headers=None, **urlopen_kw):
  • 第一个参数method为必填项,用于指定请求方法,支持'get'、'GET'、'POST'、'post'、'PUT'、'DELETE'等值,且不区分大小写。
  • 第二个参数url为必填项,指定目标URL。
  • 第三个参数fields用于传递请求参数,为可选参数。
  • 第四个参数headers用于设置请求头,为可选参数。

request方法返回的对象类型为<urllib3.response.HTTPResponse object at 0x000001B3879440B8>。

开发者可以通过dir()函数查看该对象的所有属性和方法。

例如执行dir(r)。

此处仅截取部分输出结果。

#'data', 'decode_content', 'enforce_content_length', 'fileno', 'flush', 'from_httplib',
# 'get_redirect_location', 'getheader', 'getheaders', 'headers', 'info', 'isatty',
# 'length_remaining', 'read', 'read_chunked', 'readable', 'readinto', 'readline',
# 'readlines', 'reason', 'release_conn', 'retries', 'seek', 'seekable', 'status',
# 'stream', 'strict', 'supports_chunked_reads', 'tell', 'truncate', 'version', 'writable',
# 'writelines']

二、POST请求实现

import urllib3
url = "http://httpbin.org"
fields = {
  'name':'xfy'
}
http = urllib3.PoolManager()
r = http.request('post',url+"/post",fields=fields)
print(r.data.decode())

实现过程非常简洁,仅需将第一个参数由'get'改为'post'即可。

此外,参数无需像使用urllib库时那样手动转换为byte类型。

三、设置请求头Headers

import urllib3
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
}
http = urllib3.PoolManager();
r = http.request('get',url+"/get",headers = headers)
print(r.data.decode())

四、配置代理Proxy

import urllib3
url = "http://httpbin.org"
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
}
proxy = urllib3.ProxyManager('http://101.236.19.165:8866',headers = headers)
r = proxy.request('get',url+"/ip")
print(r.data.decode())

五、发送JSON格式参数

在发起请求时,可以通过定义body参数,并在headers中指定Content-Type为application/json,从而发送已序列化的JSON数据。

import urllib3
url = "http://httpbin.org"
import json
data = {'name':'徐繁韵'}

json_data = json.dumps(data)

http = urllib3.PoolManager()
r = http.request('post',url+"/post",body = json_data,headers = {'Content-Type':'application/json'})
print(r.data.decode('unicode_escape'))

六、文件上传操作

#元组形式
with open('a.html','rb') as f:
  data = f.read()
http = urllib3.PoolManager()
r = http.request('post','http://httpbin.org/post',fields = {'filefield':('a.html',data,'text/plain')})
print(r.data.decode())

#二进制形式

r = http.request('post','http://httpbin.org/post',body = data,headers={'Content-Type':'image/jpeg'})
print(r.data.decode())

七、超时时间设置

# 1全局设置超时
# http = urllib3.PoolManager(timeout = 3)
# 2在request里设置
# http.request('post','http://httpbin.org/post',timeout = 3)

八、重试机制与重定向控制

import urllib3
http = urllib3.PoolManager()
#重试
r = http.request('post','http://httpbin.org/post',retries = 5) #请求重试测次数为5次 ,默认为3ci
print(r.retries) #Retry(total=5, connect=None, read=None, redirect=0, status=None)
#关闭重试
http.request('post','http://httpbin.org/post',retries = False) #请求重试测次数为5次 ,默认为3ci

r = http.request('get','http://httpbin.org/redirect/1',redirect = False)
print(r.retries)# Retry(total=3, connect=None, read=None, redirect=None, status=None)
print(r.status)
print(r.data.decode())
print("--------------------")
print(r.get_redirect_location())
#302不是异常

九、urllib3内置了HTTPS处理逻辑,但默认情况下会触发安全警告。

尽管请求可以成功执行,但控制台会输出如下警告信息:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

若需禁用此类警告,可执行以下代码:

import urllib3
urllib3.disable_warnings() #禁用各种警告
url = "https://www.12306.cn/mormhweb/"
http = urllib3.PoolManager()
r = http.request('get',url)
print(r.data.decode())

urllib3功能强大,但在易用性方面不如requests库,建议开发者以了解其原理为主。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。