书上有个题目,要求连接任意一个网站(他的80端口)。建立连接,然后发送字符串"GET/n",然后把返回的数据写到一个文件(我这里的文件是db.txt)里
代码如下
#!/usr/bin/env python
import socket
BufferSize = 1024
HostName = "www.baidu.com"
HostCode = 80
HostInfo = (HostName,HostCode)
ST = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #Build TCP/IP client
ST.connect(HostInfo)
ST.send("GET/\n")
db = ST.recv(BufferSize)
Files = open("db.txt","w")
for line in db:
Files.write(line)
Files.close()
ST.close()
然后我对跟换了多个网站
结果如下
www.baidu.com
文件内容完全空白
www.126.com
文件内容:
HTTP/1.0 400 Bad request
Cache-Control: no-cache
Connection: close
Content-Type: text/html
<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>
www.163.com
文件内容:
HTTP/1.0 400 Bad request
Cache-Control: no-cache
Connection: close
Content-Type: text/html
<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>
www.neotv.com.cn
文件内容
HTTP/1.1 400 Bad Request
Server: niubi_server
Date: Tue, 27 Sep 2016 14:11:41 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 270
Connection: close
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<h1>400 Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<hr/>Powered by niubi_server</body>
</html>
www.douyu.com
文件内容
HTTP/1.0 400 Bad request
Cache-Control: no-cache
Connection: close
Content-Type: text/html
<html><body><h1>400 Bad request</h1>
Your browser sent an invalid request.
</body></html>
www.sina.com.cn
这个是最特殊的,当网站改为新浪的时候,脚本运行会出错
Traceback (most recent call last):
File "16-11.py", line 10, in <module>
db = ST.recv(BufferSize)
socket.error: [Errno 104] Connection reset by peer
因为本人对web知识几乎没有,事实上我连80端口是做什么的也不知道。。。。
所以我想请问下,运行这段脚本得到的结果正常么,或者说我的脚本是否能达到书上的要求,还有就是连接新浪网出错是他网站的问题还是我的脚本的问题?