-1

I was taking the lecture on coursera and replicate the code written in the lecture video but somehow it doesn't work. The code tries to retrieve the data from a web page but got a type error.

import socket
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect(('www.py4inf.com', 80))
mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
while True:
    data = mysock.recv(512)
    if(len(data)< 1):
        break
    print(data)
mysock.close()

Error goes like this:

Traceback (most recent call last):
  File "cheese.py", line 4, in <module>
    mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')
TypeError: a bytes-like object is required, not 'str'
XYlaven
  • 21
  • 1
  • 6
  • You are sending `str` objects, but sockets only take bytes. If this is how your coursera course told you to do it, switch to Python 2, or switch courses. – Martijn Pieters Feb 28 '18 at 08:46
  • Why is this tagged [tag:bash]? Please review the tags you use before posting. – tripleee Feb 28 '18 at 09:38

1 Answers1

2

just replace

mysock.send('GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

with

mysock.send(b'GET http://www.py4inf.com/code/romeo.txt HTTP/1.0\n\n')

In Python 3, strings are codified with Unicode and sending requires a bytes-like object.

This can be made by simply putting a b in front of your string, i.e.

b'...'
Edric
  • 24,639
  • 13
  • 81
  • 91
Fanto
  • 128
  • 1
  • 9