Python3.3 HTML客户端TypeError:'str'不支持缓冲区接口 [英] Python3.3 HTML Client TypeError: 'str' does not support the buffer interface

查看:97
本文介绍了Python3.3 HTML客户端TypeError:'str'不支持缓冲区接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
  • urllib.request.urlopen
  • urllib2.urlopen
  • http
  • http.client
  • httplib

推荐答案

套接字在尝试向其发送Unicode字符串时只能接受字节.

Sockets can only accept bytes, while you are trying to send it a Unicode string instead.

将您的字符串编码为字节:

Encode your strings to bytes:

s.send("GET /robots.txt HTTP/1.0\n\n".encode('ascii'))

或给它一个字节文字(以b前缀开头的字符串文字):

or give it a bytes literal (a string literal starting with a b prefix):

s.send(b"GET /robots.txt HTTP/1.0\n\n")

请注意,您接收的数据也将是bytes值;您不能仅将它们与''进行比较.只需测试一个 empty 响应,并且您可能想在打印时将响应解码为str:

Take into account that data you receive will also be bytes values; you cannot just compare those to ''. Just test for an empty response, and you probably want to decode the response to str when printing:

while True:
    resp = s.recv(1024)
    if not resp: break
    print(resp.decode('ascii'))

这篇关于Python3.3 HTML客户端TypeError:'str'不支持缓冲区接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆