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

使用requests库无法建立连接的技术求助

Trouble connecting to Project Euler resource via Python requests library

Problem Description

I'm trying to fetch the content of a resource file from Project Euler using Python's requests library, but my code fails to run with a connection error. The website itself is accessible in a browser, so I'm wondering if there's a simple oversight causing this issue.

My Code

import requests
print(requests.get("https://projecteuler.net/project/resources/p079_keylog.txt").text)

Error Message

HTTPSConnectionPool(host='projecteuler.net', port=443): Max retries exceeded with url: /project/resources/p079_keylog.txt (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x000002701CC15128>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed',))


Answer

That getaddrinfo failed error is a classic sign that your system can't resolve the domain name to an IP address, or something is blocking the outgoing connection. Let's walk through the most likely fixes, starting with the simplest:

  • Check DNS Resolution
    The error means your computer can't look up the IP for projecteuler.net. Open your terminal and run ping projecteuler.net—if it fails to return an IP, switch your system's DNS server to a public one like Google's 8.8.8.8 or Cloudflare's 1.1.1.1. This is the most common fix for this specific error code.

  • Verify Network Restrictions
    If you're on a work, school, or VPN network, a proxy or firewall might be blocking Python's outgoing requests. Try running the code on a different network (like home Wi-Fi) or check your firewall settings to ensure the Python interpreter isn't blocked from accessing the internet.

  • Update Your Requests/Urllib3 Libraries
    Older versions of these libraries might not support the modern TLS protocols that Project Euler uses. Run this command to update them:

    pip install --upgrade requests urllib3
    
  • Add a Proper User-Agent Header
    Some websites block requests that don't include a valid user-agent (they might flag them as bots). Modify your code to include a browser-like user-agent:

    import requests
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
    }
    response = requests.get("https://projecteuler.net/project/resources/p079_keylog.txt", headers=headers)
    print(response.text)
    

Start with the DNS check first—it's usually the quickest fix here.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:06:44