公司笔记本requests/urllib模块请求失败问题求助
解决工作笔记本上requests请求超时问题
以下是几个针对性的解决步骤:
1. 手动配置企业代理
工作环境通常有专属的企业代理,但系统代理可能没被Python自动识别。先从浏览器或系统设置里找到代理地址(格式一般是http://代理地址:端口),然后在代码里手动指定:
import requests # 替换成你的实际代理地址和端口 proxies = { 'http': 'http://proxy.company.com:8080', 'https': 'http://proxy.company.com:8080' } # 如果代理需要账号密码,格式是 http://用户名:密码@proxy.company.com:8080 try: response = requests.get('https://example.org', proxies=proxies) print(response.status_code) except Exception as e: print(e)
2. 设置环境变量传递代理
也可以通过环境变量让requests自动读取代理配置:
- Windows命令行临时设置:
set HTTP_PROXY=http://proxy.company.com:8080 set HTTPS_PROXY=http://proxy.company.com:8080
设置完后再运行Python脚本,或者直接在代码里设置:
import os import requests os.environ['HTTP_PROXY'] = 'http://proxy.company.com:8080' os.environ['HTTPS_PROXY'] = 'http://proxy.company.com:8080' requests.get('https://example.org')
3. 排查网络拦截问题
- 先在命令行用
curl https://example.org测试,如果也超时,说明是企业防火墙/安全软件拦截了外部请求,需要联系IT部门把Python程序加入白名单,或者确认网络权限。 - 如果curl能正常访问,但Python不行,检查Python是否被系统防火墙禁止联网(Windows可以在“Windows Defender防火墙→允许应用通过防火墙”里找Python)。
4. 用Session对象管理请求
试试用requests的Session对象来管理代理,有时候比单次请求更稳定:
import requests session = requests.Session() session.proxies = { 'http': 'http://proxy.company.com:8080', 'https': 'http://proxy.company.com:8080' } response = session.get('https://example.org') print(response.text[:100])
内容的提问来源于stack exchange,提问作者J01
相关产品推荐
相关产品推荐

