2017-06-21 58 views
2

我想要去http://www.py4inf.com/code/romeo.txt,讀取romeo.txt的內容並將它們打印出來,使用python 3.6.1。使用套接字從網站讀取文本Python

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 

這是爲什麼內容?在此先感謝

+0

Mac的答案解決了你的問題,但我真的建議你看一下'requests'(http://docs.python-requests.org/en/master/)。讓你的生活變得如此簡單。 – fxx

+0

我會看看這個,謝謝你的建議 – Justin

回答

2

理論上,Host標頭僅從HTTP 1.1開始是必需的,但似乎特定的服務器要求存在標頭Host,即使對於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")) 

我能理解你的困惑 - 恕我直言,它應該返回400404如果在Host頭堅持所提供(自這是一個客戶端請求問題,而不是資源不存在的問題)。

+0

感謝Mac這工作! – Justin