Python3.3 HTML Client TypeError : 'str' does not support the buffer interface

标签 python html string client

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/

相关文章:

javascript - DIV 坚持到顶部,直到被下一个 DIV 推到屏幕外

javascript - IE8 通过 SendKeys 导致 FILE 输入条目为空

javascript - 整洁的内容转换,如 HTML5 bing

python - 如何仅替换\n 之后有一些字符

python - 如何用大写字母替换字符串中的小写字母并找出没有替换

python - 导入错误 : No module named <something>

python - 球员移动问题

python - 如何直接查询Django为ManyToMany关系创建的表?

python - 在一个 dict 的 dict 中,你如何模拟 Perl 的自动激活行为?

c# - 初始化的字符串似乎包含 string.Empty