跳到主要内容

🌐 Python 标准库 - urllib(网络请求与URL处理)

📌 模块简介

urllib 是 Python 内建的用于处理 URL 和 HTTP 请求的模块,包含子模块如:

  • urllib.request:发送 HTTP 请求
  • urllib.parse:解析和构建 URL
  • urllib.error:处理异常
  • urllib.robotparser:解析 robots.txt

📥 1️⃣ 下载网页数据(GET 请求)

from urllib import request

响应 = request.urlopen("[https://www.example.com](https://www.example.com)")
网页内容 = 响应.read().decode("utf-8")
print(网页内容)

📤 2️⃣ 发送 POST 请求(含表单数据)

from urllib import request, parse

数据 = parse.urlencode({"用户名": "alice", "密码": "123"}).encode("utf-8")
响应 = request.urlopen("[https://httpbin.org/post](https://httpbin.org/post)", data=数据)
print(响应.read().decode("utf-8"))

🔐 3️⃣ 添加自定义请求头(模拟浏览器)

from urllib import request

请求对象 = request.Request("[https://www.example.com](https://www.example.com)")
请求对象.add_header("User-Agent", "Mozilla/5.0")
响应 = request.urlopen(请求对象)
print(响应.status)

🔍 4️⃣ 解析 URL 结构

from urllib.parse import urlparse

结果 = urlparse("[https://www.example.com:8080/path/page?name=alice#top](https://www.example.com:8080/path/page?name=alice#top)")
print(结果.scheme) # https
print(结果.netloc) # [www.example.com:8080](http://www.example.com:8080)
print(结果.path) # /path/page

🧮 5️⃣ 构建查询字符串

from urllib.parse import urlencode

参数 = {"search": "python 编程", "页数": 2}
编码字符串 = urlencode(参数)
完整URL = f"[https://www.example.com/search?{编码字符串}](https://www.example.com/search?{编码字符串})"
print(完整URL)

🚧 6️⃣ 捕获异常

from urllib import request, error

try:
响应 = request.urlopen("[https://不存在的网址.com](https://不存在的网址.com)")
except error.URLError as e:
print("发生错误:", e.reason)

🤖 7️⃣ 检查网站是否允许爬取(robots.txt)

from urllib.robotparser import RobotFileParser

解析器 = RobotFileParser()
解析器.set_url("[https://www.example.com/robots.txt](https://www.example.com/robots.txt)")
解析器.read()
允许访问 = 解析器.can_fetch("*", "[https://www.example.com/data](https://www.example.com/data)")
print("允许访问" if 允许访问 else "禁止访问")

✅ 小结:常用模块功能表

模块功能说明
urllib.request发送 HTTP 请求
urllib.parse解析/构建 URL
urllib.error捕获请求错误
urllib.robotparser分析 robots.txt