1

I'm very confused on how to save my image after 'getting' it using requests/sessions! Please note that url, img_name, and img_end are all defined above, they take a static URL and add numbers to the end to request images corresponding to those numbers.

s = requests.Session()
s.auth = ('username', 'password')
s.headers.update({'x-test': 'true'})
s.get(url+img_name+img_end, headers={'x-test2': 'true'})

If I do print(s) I get <requests.sessions.Session object at 0x036A3710> which leads to think that my image is downloading. However if I do something like save_img = Image.open(s) I get a response that Session has no attribute read. If anyone can explain how to save the image that I requested to a file that would be amazing, I'm new to Python and this part isn't making sense. Also if my code above is wrong I basically copied the examples from http://docs.python-requests.org/en/master/user/advanced/ for what it's worth.

1 Answer 1

2

<requests.sessions.Session object at 0x036A3710> is the session object itself in memory, and has nothing to do with the image, so don't let that confuse you (any instance of a Python object has an address in memory).

The get function will return the data you want, so you have to store it using a variable:

data = s.get(url+img_name+img_end, headers={'x-test2': 'true'})
with open('image', 'wb') as fobj:
    fobj.write(data.content)
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! That seems to work, however, why does the file that I output seem to be corrupt and/or contain no real data? I can't open the image, but it is 370kb so there is something?
Are you saving it with the correct file extension, e.g. open('image.jpg', 'wb')?
yes, I've tried .jpg and .png, both formats I get an output that is 370KB but there is not an image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.