0

这就是响应的样子

HTTP/1.1 301 Moved Permanently
Location: http://www.google.com/
Content-Type: text/html; charset=UTF-8
Date: Fri, 11 Sep 2015 19:18:15 GMT
Expires: Sun, 11 Oct 2015 19:18:15 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 219
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

我想获取空行的索引,我试过了

response.index("\n\n")

但它不起作用。

有什么建议么?

谢谢你!

编辑:它给了我这个

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    test = response.index("\n\n")
ValueError: substring not found

这是我的完整代码:

import socket

server = "www.google.com"
server = socket.gethostbyname(server)
port = 80
request = "GET / HTTP/1.1\nHost: " + server + "\n\n"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((server, port))
sock.send(request.encode())

response = sock.recv(4096)
print(response)

test = response.index("\n\n")

print(test)
4

1 回答 1

0

编辑:看到你的整个代码后,很容易看出接收到的数据是编码的,你需要解码数据。

重要的部分是response = sock.recv(4096).decode("utf-8")将字节数组转换为python中的字符串。

这段代码对我有用。

import socket

server = "www.google.com"
server = socket.gethostbyname(server)
port = 80
request = "GET / HTTP/1.1\nHost: " + server + "\n\n"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.connect((server, port))
sock.send(request.encode())

response = sock.recv(4096).decode("utf-8")
print(response)

test = response.index("\r\n\r")

print(test)
于 2015-09-11T21:02:57.953 回答