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

13,122

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

Solution 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")
Share:
13,122
CaseyJames22
Author by

CaseyJames22

Updated on June 04, 2022

Comments

  • CaseyJames22
    CaseyJames22 almost 2 years
    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