Skip to main content
 首页 » 编程设计

python之使用 Python 套接字从网站读取文本

2024年10月01日8JustinYoung

我正在尝试前往 http://www.py4inf.com/code/romeo.txt , 读取 romeo.txt 的内容并将它们打印出来,我使用的是 python 3.6.1。

import socket 
 
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
mysock.connect(('www.py4inf.com', 80)) 
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n'.encode("utf8")) 
 
while True: 
    data = mysock.recv(512) 
    if ( len(data) < 1 ) : 
        break 
    print (data.decode("utf8")) 
 
mysock.close() 

而不是它打印出的页面内容

TTP/1.1 404 Not Found 
Server: nginx 
Date: Wed, 21 Jun 2017 03:00:15 GMT 
Content-Type: text/html 
Content-Length: 162 
Connection: close 
 <html> 
<head><title>404 Not Found</title></head> 
<body bgcolor="white"> 
<center><h1>404 Not Found</h1></center> 
<hr><center>nginx</center> 
</body> 
</html 

这是为什么?提前致谢

请您参考如下方法:

理论上,Host header 仅在 HTTP 1.1 之后是强制性的,但似乎特定服务器要求存在 Host header ,即使对于 HTTP 1.0。我不确定这是否是 Nginx 的默认行为,或者服务器管理员是否以这种方式明确配置它。

无论如何,请尝试将您的请求更改为以下内容:

mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\nHost: www.py4inf.com\n\n'.encode("utf8")) 

我能理解你的困惑 - 恕我直言,如果它坚持提供 Host header ,它应该返回 400 而不是 404 (因为这是客户端请求问题,而不是资源不存在的问题)。