悠悠楠杉
网站页面
正文:
在Python中,urllib.request.urlopen()是一个强大的工具,用于发送HTTP请求并获取响应数据。无论是爬虫开发、API调用还是简单的网页内容抓取,urlopen()都能轻松应对。本文将带你从基础到实战,全面掌握这一功能。
urlopen()是urllib.request模块的核心函数,支持GET、POST等请求方式。以下是一个最简单的GET请求示例:
from urllib.request import urlopen
response = urlopen("https://www.example.com")
print(response.read().decode('utf-8')) # 输出网页HTML内容
这段代码会请求example.com的首页并打印HTML内容。注意:read()方法返回字节流,需用decode()转换为字符串。
网络请求可能因超时或URL错误而失败,urlopen()提供了异常处理机制:
from urllib.error import URLError, HTTPError
try:
response = urlopen("https://invalid.url", timeout=5)
except HTTPError as e:
print(f"HTTP错误: {e.code}")
except URLError as e:
print(f"URL错误: {e.reason}")
通过timeout参数可设置超时时间(单位:秒),避免程序长时间阻塞。
若需提交数据(如API调用),可通过data参数传递POST请求体,并自定义请求头:
import urllib.parse
data = urllib.parse.urlencode({"key": "value"}).encode('utf-8')
headers = {"User-Agent": "Mozilla/5.0"}
req = urllib.request.Request(
url="https://httpbin.org/post",
data=data,
headers=headers
)
response = urlopen(req)
print(response.read().decode())
这里使用urlencode将字典转换为表单格式,并通过Request对象设置请求头。
结合json模块,可快速处理API返回的JSON数据。以下示例获取天气API数据:
import json
url = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY"
response = urlopen(url)
data = json.loads(response.read())
print(f"伦敦温度: {data['main']['temp']}K")
requests库(基于连接池)。Content-Type,避免解码错误。context=ssl.create_default_context())。