我编写了一个 python 代码,它将通过连接到端口 80 并发送 GET http 请求从 Web 服务器获取数据。但这并没有给我网页的数据,而是给了我一个 html 代码,上面写着“网页已移动”。
请帮助我
下面是代码和示例输出
import socket
def web_client():
host=str(input("\nEnter the site from which you want to recieve data \n\n -> "))
port=80
s=socket.socket()
ip=socket.gethostbyname(host)
s.connect((ip, port))
print("\nconnection successful with "+ str(host)+" on ip "+str(ip))
msg="GET / HTTP/1.1\r\n\r\n"
encoded_msg=bytes(msg, "utf-8")
s.send(encoded_msg)
data=s.recv(2048)
decoded_data=data.decode("utf-8")
print("\n"+decoded_data)
web_client()
我输入“www.google.com”时得到的输出如下所示
Enter the site from which you want to recieve data
-> www.google.com
connection successful with www.google.com on ip 216.58.220.36
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.co.in/?gfe_rd=cr&ei=k09IVbiMKq_v8wez3oGICw
Content-Length: 261
Date: Tue, 05 May 2015 05:05:23 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic,p=1
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/?gfe_rd=cr&ei=k09IVbiMKq_v8wez3oGICw">here</A>.
</BODY></HTML>