我正在尝试从 here 获取可见内容使用 socket
但不幸的是,我在执行脚本时遇到错误。由于我对使用 socket
编写代码非常陌生,所以我不明白我哪里出了问题。
我的代码:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_ip = socket.gethostbyname('data.pr4e.org')
s.connect((host_ip,80))
cmd = "GET http://data.pr4e.org/romeo.txt HTTP/1.0\n\n".encode()
s.send(cmd)
while True:
data = s.recv(1024)
if (len(data) <1 ):
break
print(data.decode())
s.close()
我遇到的错误:
400 Bad Request
Your browser sent a request that this server could not understand.
最佳答案
通过将 \r\n\r\n
添加到请求命令的末尾,而不是原来的 \n\n
,我能够获得所需的结果>:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostbyname('data.pr4e.org'), 80))
s.sendall("GET http://data.pr4e.org/romeo.txt HTTP/1.0\r\n\r\n".encode())
print(s.recv(1024))
输出:
...
Content-Type: text/plain\r\n\r\nBut soft what light through yonder window breaks\nIt is the east and Juliet is the sun\nArise fair sun and kill the envious moon\nWho is already sick and pale with grief\n'
关于python - 无法使用套接字获取所需内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53026133/