苦练Python第70天:征服网络请求!揭开urllib.request的神秘面纱

前言

大家好,我是 倔强青铜三 。欢迎关注我,微信公众号: 倔强青铜三。点赞、收藏、关注,一键三连!

你能否想象不安装任何第三方库 就能从网上爬数据?当初学者们都在追捧requests库时,Python自带的核武器却被忽略了!

今天带你用urllib.request打开网络编程新世界,全程无第三方依赖,只需原生Python!


一、模块定位与作用

urllib.request是Python标准库中的HTTP瑞士军刀,无需额外安装 ,直接import即可。它能完成:

  • 发送HTTP/HTTPS请求
  • 添加请求头、Cookie等认证信息
  • 处理文件上传/下载
  • 管理网络代理和重定向

📌 记住:Python自带的标准库永远是最高性价比的学习选择!


二、发送GET请求实战

urlopen()发起首个请求:

python 复制代码
import urllib.request  

# 获取示例网站内容  
with urllib.request.urlopen("https://httpbin.org/get") as response:  
    status = response.status  
    headers = dict(response.getheaders())  
    content = response.read().decode("utf-8")  

print(f"状态码: {status}")  
print(f"响应头类型: {headers.get('Content-Type')}")  
print(f"内容片段: {content[:200]}...")  

运行结果

makefile 复制代码
状态码: 200  
响应头类型: application/json  
内容片段: {  
  "args": {},  
  "headers": {  
    "Accept-Encoding": "identity",  
    "Host": "httpbin.org",  
    "User-Agent": "Python-urllib/3.10",  
    ...  
  },  
  "origin": "xxx.xxx.xxx.xxx",  
  "url": "https://httpbin.org/get"...  

💡 关键点:

  1. with语句自动关闭网络连接
  2. response.read()返回bytes类型数据
  3. 需用.decode('utf-8')转为字符串

三、伪装浏览器:自定义请求头

许多网站屏蔽Python默认UA(User-Agent),用Request对象突破封锁:

python 复制代码
import urllib.request  

# 伪装Chrome浏览器  
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124"}  
req = urllib.request.Request(  
    url="https://httpbin.org/user-agent",  
    headers=headers  
)  

# 发送请求  
with urllib.request.urlopen(req) as response:  
    print(response.read().decode('utf-8'))  

运行结果

json 复制代码
{  
  "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124"  
}  

👉 网站看到的是伪装后的浏览器标识!


四、POST请求提交表单数据

实现登录等操作必须掌握POST:

python 复制代码
import urllib.request  
import urllib.parse  

# 构造表单数据  
form_data = {"user": "admin", "pass": "secret123"}  
encoded_data = urllib.parse.urlencode(form_data).encode("utf-8")  

# 创建POST请求  
req = urllib.request.Request(  
    url="https://httpbin.org/post",  
    data=encoded_data,  
    method="POST"  
)  

# 发送并获取结果  
with urllib.request.urlopen(req) as response:  
    print(response.read().decode("utf-8"))  

运行结果

json 复制代码
{  
  "form": {  
    "pass": "secret123",  
    "user": "admin"  
  },  
  "headers": {  
    "Content-Length": "25",  
    "Content-Type": "application/x-www-form-urlencoded"  
  },  
  ...  
}  

🚨 注意:

  1. 数据必须用urlencode()处理
  2. 要转成bytes类型:.encode('utf-8')
  3. 显式指定method='POST'

五、异常处理:躲开90%的崩溃场景

网络请求充满不确定性,必须添加异常处理:

python 复制代码
import urllib.error  

targets = [  
    "https://不存在的网站.com",  # 域名错误  
    "https://httpbin.org/status/404",  # 404页面  
]  

for url in targets:  
    try:  
        with urllib.request.urlopen(url) as response:  
            print(f"{url} 访问成功")  
    except urllib.error.URLError as e:  
        print(f"⚠️ {url} 访问失败: {e.reason}")  
    except urllib.error.HTTPError as e:  
        print(f"🔴 {url} 服务器错误: {e.code} {e.msg}")  

运行结果

arduino 复制代码
⚠️ https://不存在的网站.com 访问失败: [Errno 11001] getaddrinfo failed  
🔴 https://httpbin.org/status/404 服务器错误: 404 NOT FOUND  

六、终极实战:保存网页到本地

综合应用所有知识:

python 复制代码
import urllib.request  
import urllib.error  

url = "http://example.com"  
file_path = "example.html"  

try:  
    # 设置浏览器UA头  
    req = urllib.request.Request(  
        url,  
        headers={"User-Agent": "Mozilla/5.0"}  
    )  
    
    # 超时设置为10秒  
    with urllib.request.urlopen(req, timeout=10) as response:  
        # 检测内容编码  
        content_type = response.headers.get("Content-Type")  
        encoding = "utf-8"  
        if "charset=" in content_type:  
            encoding = content_type.split("charset=")[-1]  
        
        # 写入文件  
        html = response.read().decode(encoding)  
        with open(file_path, "w", encoding=encoding) as f:  
            f.write(html)  
        print(f"网页已保存至 {file_path}")  

except Exception as e:  
    print(f"❌ 抓取失败: {str(e)}")  

运行结果

复制代码
网页已保存至 example.html  

👉 打开example.html可看到完整的Example首页


避坑指南(血泪总结)

  1. 乱码问题

    • 优先使用response.headers.get('Content-Type')中的编码
  2. 超时崩溃

    调用时设置urlopen(url, timeout=10)

  3. HTTPS证书错误

    测试环境可临时忽略:

    python 复制代码
    import ssl  
    context = ssl._create_unverified_context()  
    response = urllib.request.urlopen(url, context=context)  
  4. 🌟 永远记住

  • 商业项目需设置请求间隔时间避免封IP
  • 检查网站的robots.txt遵守爬虫规则
  • 敏感数据必须使用HTTPS传输

掌握这些技巧后,用纯Python标准库处理网络请求将畅通无阻!

最后感谢阅读!欢迎关注我,微信公众号: 倔强青铜三
点赞、收藏、关注 ,一键三连!!

欢迎 点击 【👍喜欢作者】 按钮进行 打赏💰💰,请我喝一杯咖啡☕️!

相关推荐
Anhty3 分钟前
2026九月最新变声器测评:iOS安卓双端适配,低延迟运行更稳定
android·人工智能·功能测试·ios·智能手机
禹凕11 分钟前
滑动窗口算法实战指南
python·算法
DisonTangor17 分钟前
【腾讯混元雪耻归来】 Hy4 preview:770B 参数 MoE 旗舰模型,1M 上下文全面开源
人工智能·算法·开源·aigc·腾讯云·腾讯云ai代码助手
luckystar513~25 分钟前
Hermes 实战 :系列收官/生产化——安全审计与运维
运维·人工智能·安全·agent·智能体开发·hermes实战·智能体网关
Mickey Q41 分钟前
【深度学习】数值稳定性和模型初始化
人工智能·深度学习
冬奇Lab1 小时前
Code Agent 解剖(20):从零扩展——给 agent 加一个新工具
人工智能·开源
论文复现现场1 小时前
RTX 4090 24GB 能跑 Qwen3.8-27B 吗?单卡显存计算与云端部署指南
人工智能·python·云计算·llama·gpu算力
七牛云行业应用1 小时前
Harness Engineering 是什么:从“写提示词“到“设计 Agent 边界“的工程方法论
人工智能·agent·ai编程
Patrick在香港1 小时前
模型路由器实测:12 个任务省 77%,旗舰过载时的降级要打出显式标记
python·llm·智能路由器·api·架构设计·成本优化
科技拓维者1 小时前
短视频配音音效去哪里找比较好?短视频创作者音效指南
人工智能·音视频