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

不想你离开。 提交于 2019-12-22 10:59:59

问题


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

Error:

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

Can NOT use

  • urllib.request.urlopen
  • urllib2.urlopen
  • http
  • http.client
  • httplib

回答1:


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'))

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

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'))



回答2:


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


来源:https://stackoverflow.com/questions/26537592/python3-3-html-client-typeerror-str-does-not-support-the-buffer-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!