Python Forum

Full Version: variable as byte
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been learning Python from 'Python for Everybody' by Charles Severance and found it very good
However, I have used his suggested code for downloading an image from a webpage and though I have checked it a few times and tried some alternatives, I always get a Traceback message
Error:
fhand.write(picture) TypeError: a bytes-like object is required, not 'int'
The ocde is copied below. Could some kind person please spot the mistake! Not sure if it's me or a misprint of course
Many thanks! Jessica
import socket
import time

HOST='data.pr4e.org'
PORT = 80
mysock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysock.connect((HOST,PORT))
mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n')
count = 0
picture = b""

while True:
    data = mysock.recv(5120)
    if len(data)<1: break
    #time.sleep(0.25)
    count = count + len(data)
    print(len(data),count)
    picture = picture + data

mysock.close()

#look for end of header
pos = picture.find(b"\r\n\r\n")
print("Header length",pos)
print(picture[:pos].decode())

#skip header and save picture data

picture = picture[pos+4]




fhand = open("stuff.jpg",'wb')
print("got this far")
fhand.write(picture)
fhand.close()