使用requests库无法建立连接的技术求助
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 forprojecteuler.net. Open your terminal and runping 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 urllib3Add 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

