matheus
matheus

Reputation: 107

Trying to get an image with python

I am trying to get an image from a website and I don't know what i am doing wrong. Here is my code:

import httplib2

h = httplib2.Http('.cache')

response, content = h.request('http://1.bp.blogspot.com/-KSBzFF0bIyU/TtFyj-KgC0I/AAAAAAAABEo/o43IoY_9Bec/s1600/praia-de-ponta-verde-maceio.jpg')

print(response.status)

with open('maceio.jpg', 'wb') as f:
    print(content, file = f)

--------------------------------------------------------------------------------

 200
Traceback (most recent call last):
  File "/home/matheus/workspace/Get Link/new_method_v2.py", line 12, in <module>
    print(content, file = f)
TypeError: 'str' does not support the buffer interface

Upvotes: 0

Views: 525

Answers (1)

Ferdinand Beyer
Ferdinand Beyer

Reputation: 67137

The error is caused by the following line:

print(content, file = f)

print implicitely converts the bytes object named content to a string (str object), which cannot be written to a file in binary mode, since Python does not know which character encoding to use.

Why are you taking the print detour at all? Just write the contents to the file using the file.write() method:

with open('maceio.jpg', 'wb') as f:
    f.write(content)

Upvotes: 2

Related Questions