Python3.3 HTML客户端类型错误:'str'不支持缓冲区接口

3 投票
2 回答
13137 浏览
提问于 2025-04-29 08:31
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
暂无标签

2 个回答

1

在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。比如,有人可能会在使用某个库时,发现它的某个功能没有按预期工作。这种情况下,我们就需要去查找解决方案,看看有没有人遇到过类似的问题。

通常,我们可以在网上找到很多资源,比如论坛、文档或者问答网站。在这些地方,其他开发者可能分享了他们的经验和解决办法。通过这些信息,我们可以更快地找到问题的根源,并找到合适的解决方案。

总之,遇到问题时,不要慌张,先去查找相关的资料,看看有没有人已经解决了类似的问题,这样可以节省很多时间和精力。

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")
8

套接字(Sockets)只能接收字节,而你现在试图发送的是一个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'))

撰写回答