使用HTTP协议获取网页信息遇socket.gaierror等问题求助
socket.gaierror in your Python socket code Hey there! Let's break down what's causing that socket.gaierror: [Errno 11001] getaddrinfo failed error and how to fix it.
The core issue
Your mistake is in the connect() call: you're passing a full URL (http://data.pr4e.org/intro-short.txt) as the host parameter, but the socket connect() method only expects the hostname (or IP address) and port number. The getaddrinfo function can't resolve URLs with the http:// prefix or file path attached, which is why you're getting that DNS resolution error—and why your telnet attempt failed too (you probably tried telnetting to the full URL instead of just the hostname).
Corrected code
Here's the fixed version of your code with the key change highlighted:
import socket mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Changed from full URL to just the hostname: data.pr4e.org mysock.connect(('data.pr4e.org', 80)) cmd = 'GET http://data.pr4e.org/intro-short.txt HTTP/1.0\r\n\r\n'.encode() mysock.send(cmd) while True: data = mysock.recv(512) if len(data) < 1: break print(data.decode(), end='') mysock.close()
What this fixes
- The
connect()call now targets the correct hostname (data.pr4e.org) on port 80, whichgetaddrinfocan resolve properly. - The
GETrequest still includes the full path to the file (/intro-short.txt) as part of the HTTP command, which is exactly what the server expects.
When you run this corrected code, you should see the full HTTP response (including metadata headers like Content-Type and Content-Length) followed by the content of the intro-short.txt file.
As a side note: while using raw sockets is great for learning how HTTP works under the hood, in real-world Python code, you'd usually use libraries like requests to handle HTTP requests more cleanly. But since you're working through the Python for Everybody course, sticking with the socket approach makes perfect sense for building foundational knowledge!
内容的提问来源于stack exchange,提问作者Vishal Pallikonda

