Reputation: 15
In Python, when I run this code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
s=socket.socket()
s.connect(('www.sina.com.cn',80))
s.send(b'GET /HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
buffer=[]
while True:
d=s.recv(1024)
if d:
buffer.append(d)
else:
break
data=b''.join(buffer)
s.close()
header,html = data.split(b'\r\n\r\n',1)
print(header.decode('utf-8'))
with open('sina_test.html','wb') as f:
f.write(html)
I get this error:
line 19, in (header,html,h) = data.split(b'\r\n\r\n',1) ValueError: need more than 1 value to unpack
What does that error mean?
Upvotes: 0
Views: 3813
Reputation: 11
There's a SPACE before the HTTP
# wrong
s.send(b'GET /HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
# correct
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
The wrong usage maybe send you this information:
print(data)
<HTML>\n<HEAD>\n<TITLE>Not Found on Accelerator</TITLE>\n</HEAD>\n\n<BODY BGCOLOR="white" FGCOLOR="black">\n<H1>Not Found on Accelerator</H1>\n<HR>\n\n<FONT FACE="Helvetica,Arial"><B>\nDescription: Your request on the specified host was not found.\nCheck the location and try again.\n</B></FONT>\n<HR>\n</BODY>\n
The right information is just like this:
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 23 Jan 2018 03:28:38 GMT
Content-Type: text/html
Content-Length: 605221
Connection: close
Last-Modified: Tue, 23 Jan 2018 03:27:02 GMT
Vary: Accept-Encoding
Expires: Tue, 23 Jan 2018 03:29:37 GMT
Cache-Control: max-age=60
X-Powered-By: shci_v1.03
Age: 1
Via: http/1.1 ctc.jiangsu.ha2ts4.82 (ApacheTrafficServer/6.2.1 [cHs f ])
X-Cache: HIT.82
X-Via-CDN: f=edge,s=ctc.jiangsu.ha2ts4.83.nb.sinaedge.com,c=58.213.91.6;f=Edge,s=ctc.jiangsu.ha2ts4.82,c=61.155.142.83
X-Via-Edge: 1516678118627065bd53afa8e9b3d553f23b9
That's why ValueError occurs.
Upvotes: 1
Reputation: 6181
This error means that your string (data
) does not contain the regex you are trying to split accordingly and therefore - data.split(b'\r\n\r\n',1) == data
which cannot be assigned to header and html.
Upvotes: 0
Reputation: 8300
The second argument to split
method limits how many items the method will return
header,html = data.split(b'\r\n\r\n',1)
Here you are trying to unpack more than 1 even though you specified that split
should only return 1 item
Upvotes: 1