我这样做算成功了么。。。。

加盾男爵 2016-09-27 10:23:59
书上有个题目,要求连接任意一个网站(他的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端口是做什么的也不知道。。。。
所以我想请问下,运行这段脚本得到的结果正常么,或者说我的脚本是否能达到书上的要求,还有就是连接新浪网出错是他网站的问题还是我的脚本的问题?
...全文
189 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ForestDB 2016-09-28
  • 打赏
  • 举报
回复
结果正常,代码基本上也正确,只是 ST.send("GET/\n") GET/\n并不是个合法的HTTP请求 GET / HTTP/1.1\n\n才是个基本的合法的HTTP请求。 但即使发送这个请求,服务器也有可能不返回首页,应为该请求缺少一些常见的请求头,会被服务器判为“模拟”的请求而拒绝服务。 去看看基本的web知识。

37,737

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧