代码示例
import urllib.request
url = 'https://www.baidu.com/s?wd=ip'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
}
# 请求对象的定制
request = urllib.request.Request(url=url, headers=headers)
# 代理设置
proxies = {
'http': '49.67.109.216:15600', # 注意代理格式
'https': '49.67.109.216:15600' # 如果同时支持https代理,需指定
}
# 设置代理处理器
handler = urllib.request.ProxyHandler(proxies)
opener = urllib.request.build_opener(handler)
# 发送请求并获取响应
try:
response = opener.open(request)
content = response.read().decode('utf-8')
# 保存数据到本地
with open('handler.html', 'w', encoding='utf-8') as f:
f.write(content)
print("数据已成功保存到 handler.html")
except Exception as e:
print(f"请求失败: {e}")
代码规范
-
代理格式问题:在
proxies字典中,代理地址和端口号应该写为'http://ip:port'的形式。 -
代码规范:应该增加代码的可读性,调整代码格式,增加适当的注释和空行。
-
异常处理:建议在网络请求中加入异常处理,以避免因网络问题导致程序崩溃。