我正在尝试通过Python套接字库向网站发出简单的HTTP GET请求。我在这里使用的示例网站是https://azlyrics.com/lyrics/charlieputh/attention.html。我的代码是:
from socket import *
serverName = 'azlyrics.com';
serverPort = 80;
clientSocket = socket(AF_INET, SOCK_STREAM);
print(clientSocket.connect((serverName, serverPort)));
message = '''GET /lyrics/charlieputh/attention.html HTTP/1.1
Host: www.azlyrics.com
Connection: keep-alive
''';
print(message);
clientSocket.send(message.encode());
modifiedMessage = clientSocket.recv(2048).decode();
print(modifiedMessage);
clientSocket.close();
但是我没有得到任何回应消息。同样,我得到的connect()
返回对象是None。我已经使用Python请求库尝试了相同的URL,并且工作正常。我在这里做什么错了?
答案 0 :(得分:0)
HTTP请求正文应以\r\n
(CR-LF)结尾
请尝试以下操作:
from socket import *
serverName = 'azlyrics.com';
serverPort = 80;
clientSocket = socket(AF_INET, SOCK_STREAM);
print(clientSocket.connect((serverName, serverPort)));
message = '''GET /lyrics/charlieputh/attention.html HTTP/1.1
Host: www.azlyrics.com
Connection: keep-alive
''';
print(message);
clientSocket.send(message.encode());
modifiedMessage = clientSocket.recv(2048).decode();
print(modifiedMessage);
clientSocket.close();