import socket
# Set up a TCP/IP socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# Connect as client to a selected server
# on a specified port
s.connect(("www.wellho.net",80))
# Protocol exchange - sends and receives
s.send("GET /robots.txt HTTP/1.0\n\n")
while True:
resp = s.recv(1024)
if resp == "": break
print(resp,)
# Close the connection when completed
s.close()
print("\ndone")
错误:
cg0546wq@smaug:~/Desktop/440$ python3 HTTPclient.py
Traceback (most recent call last):
File "HTTPclient.py", line 11, in <module>
s.send("GET /robots.txt HTTP/1.0\n\n")
TypeError: 'str' does not support the buffer interface
不能使用
urllib.request.urlopen
urllib2.urlopen
http
http.client
httplib
最佳答案
套接字只能接受字节,而您正试图向它发送一个 Unicode 字符串。
将字符串编码为字节:
s.send("GET /robots.txt HTTP/1.0\n\n".encode('ascii'))
或者给它一个字节文字(以 b
前缀开头的字符串文字):
s.send(b"GET /robots.txt HTTP/1.0\n\n")
考虑到您接收 的数据也将是字节
值;您不能只将它们与 ''
进行比较。只需测试一个空 响应,您可能希望在打印时将响应解码为 str
:
while True:
resp = s.recv(1024)
if not resp: break
print(resp.decode('ascii'))
关于Python3.3 HTML Client TypeError : 'str' does not support the buffer interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26537592/