使用Python requests库遇[Errno 11001] getaddrinfo failed错误求助
问题描述
- 已安装
requests库,按照官方快速入门文档示例执行请求,替换URL为https://www.google.com后仍报错 - 当前处于代理网络环境
- 错误详情:
>>> import requests >>> r = requests.get('https://api.github.com/events') Traceback (most recent call last): File "C:\User\venv\lib\site-packages\urllib3\connection.py", line 203, in _new_conn sock = connection.create_connection( File "C:\User\venv\lib\site-packages\urllib3\util\connection.py", line 60, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "C:\Program Files\Python39\lib\socket.py", line 954, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno 11001] getaddrinfo failed
解决方案
这个错误是代理环境下requests未配置代理导致DNS解析失败,以下是几种可行解决方式:
1. 请求时直接指定代理
在get方法中传入proxies参数,替换为你的代理地址和端口:
import requests proxies = { 'http': 'http://your-proxy-address:port', 'https': 'http://your-proxy-address:port', } r = requests.get('https://api.github.com/events', proxies=proxies)
若代理需用户名密码,格式如下:
proxies = { 'http': 'http://username:password@your-proxy-address:port', 'https': 'http://username:password@your-proxy-address:port', }
2. 配置系统环境变量
设置HTTP_PROXY和HTTPS_PROXY环境变量,requests会自动读取:
- Windows命令行执行:
set HTTP_PROXY=http://your-proxy-address:port set HTTPS_PROXY=http://your-proxy-address:port
需用户名密码时:
set HTTP_PROXY=http://username:password@your-proxy-address:port set HTTPS_PROXY=http://username:password@your-proxy-address:port
设置完成后重启Python环境即可生效。
3. 创建Session持久化代理
如果需要多次请求复用代理,可创建Session对象并配置:
import requests session = requests.Session() session.proxies = { 'http': 'http://your-proxy-address:port', 'https': 'http://your-proxy-address:port', } r = session.get('https://api.github.com/events')
内容的提问来源于stack exchange,提问作者IceTea
相关产品推荐
相关产品推荐

