[英]TypeError: 'str' does not support the buffer interface - python
[英]Python3.3 HTML Client TypeError: 'str' does not support the buffer interface
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")
考慮到您收到的數據也將是bytes
值; 你不能只將它們與''
進行比較。 只測試一個空響應,你可能想要在打印時解碼對str
的響應:
while True:
resp = s.recv(1024)
if not resp: break
print(resp.decode('ascii'))
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.google.com",80))
# Protocol exchange - sends and receives
s.send(b"GET /index.html HTTP/1.0\n\n")
while True:
resp = s.recv(1024)
if resp == b'': break
print(resp,)
# Close the connection when completed
s.close()
print("\ndone")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.