TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码

pythonurlopen()「建议收藏」

2026-01-05
/
0 评论
/
45 阅读
/
正在检测是否收录...
01/05

正文:

在Python中,urllib.request.urlopen()是一个强大的工具,用于发送HTTP请求并获取响应数据。无论是爬虫开发、API调用还是简单的网页内容抓取,urlopen()都能轻松应对。本文将带你从基础到实战,全面掌握这一功能。

1. 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()转换为字符串。

2. 处理异常与超时

网络请求可能因超时或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参数可设置超时时间(单位:秒),避免程序长时间阻塞。

3. 发送POST请求与请求头设置

若需提交数据(如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对象设置请求头。

4. 实战:抓取并解析JSON数据

结合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")  

5. 性能优化与注意事项

  • 连接复用:频繁请求时,考虑使用requests库(基于连接池)。
  • 编码处理:检查响应头的Content-Type,避免解码错误。
  • HTTPS安全:必要时添加SSL验证(如context=ssl.create_default_context())。
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/42548/(转载时请注明本文出处及文章链接)

评论 (0)
37,548 文章数
92 评论量

人生倒计时

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月