You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地运行Requests报Connection refused但Google Colab可正常运行求解

问题描述

尝试用以下Python代码爬取目标网站:

search_url = 'http://www.p***hub.com/'
response = requests.get(search_url)

本地运行时收到错误:

HTTPConnectionPool(host='www.p***hub.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f61969838d0>: Failed to establish a new connection: [Errno 111] Connection refused'))

但相同脚本在Google Colab上能正常运行,尝试更换多个代理后仍出现相同错误。

解决方案

  • 排查本地网络限制:目标网站可能被本地运营商、防火墙或杀毒软件拦截。先尝试用浏览器直接访问该网站,若无法打开,说明是网络屏蔽问题,需调整网络环境(注意遵守当地网络法规);临时关闭防火墙/杀毒软件后重试请求。
  • 补充请求头信息:目标网站可能验证请求的User-Agent字段,添加合规的请求头再尝试:
    search_url = 'http://www.p***hub.com/'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
    }
    response = requests.get(search_url, headers=headers)
    
  • 修正代理配置:确认代理的地址、端口、认证信息是否正确,先测试代理能否访问其他普通网站(如百度),确保代理有效。示例带认证的代理配置:
    proxies = {
        'http': 'http://user:pass@proxy_ip:port',
        'https': 'http://user:pass@proxy_ip:port'
    }
    response = requests.get(search_url, headers=headers, proxies=proxies)
    
  • 改用HTTPS协议:目标网站可能强制使用HTTPS,将URL改为https://www.p***hub.com/再发起请求。

内容的提问来源于stack exchange,提问作者Brombeere1996

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:14:08