Этот код работал для меня:
import socket
from urllib.parse import urlsplit
url = urlsplit('http://www.py4inf.com/code/romeo.txt')
host = url.hostname
path = url.path
request = f'GET {path} HTTP/1.1\nHost: {host}\n\n'.encode('utf-8')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, 80))
s.send(request)
result = s.recv(10000)
while (len(result) > 0):
print(result.decode('utf-8'))
А вот вывод кода выше:
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 167
Connection: keep-alive
Keep-Alive: timeout=15
Date: Thu, 09 May 2019 08:49:50 GMT
Server: Apache
Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
ETag: "a7-526172f58b800"
Accept-Ranges: bytes
Cache-Control: max-age=604800, public
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
Редактировать: здесь исправлен ваш оригинальный код:
import socket
from urllib.parse import urlsplit
url = urlsplit(input("Enter a URL: ").strip())
count = 0
host = url.hostname
path = url.path
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print(f'Connecting to {host} and fetching {path}')
s.connect((host, 80))
cmd = f'GET {path} HTTP/1.1\nHost: {host}\n\n'.encode('utf-8')
s.send(cmd)
except:
print("Enter a valid URl")
exit()
while True:
data = s.recv(512)
count += len(data)
if len(data) < 1:
break
print(data.decode())
s.close()
А вот вывод, который я получаю, используя приведенный выше код:
Enter a URL: http://www.py4inf.com/code/romeo.txt
Connecting to www.py4inf.com and fetching /code/romeo.txt
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 167
Connection: keep-alive
Keep-Alive: timeout=15
Date: Thu, 09 May 2019 15:30:16 GMT
Server: Apache
Last-Modified: Fri, 04 Dec 2015 19:05:04 GMT
ETag: "a7-526172f58b800"
Accept-Ranges: bytes
Cache-Control: max-age=604800, public
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Access-Control-Allow-Methods: GET
But soft what light through yonder window breaks
It is the east and Juliet
is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief