0 votes
1 view
in Data Science by (17.6k points)

I need to download an image from a url using Python. I'm using this to do so:

import requests

with requests.get(url, stream=True) as r:

    with open(img_path, "wb") as f:


In order for me to see the image in the browser, I need to be logged into my account on that site. The image may have been sent by someone else or myself.

The issue is that I am able to download some images successfully, but for other ones, I get an authentication error, i.e. that I'm not logged in.

In that case too, sometimes it downloads a file whose content is this:

{"result":"error","msg":"Not logged in: API authentication or user session required"}

And sometimes, it downloads the html file of the webpage which asks me to login to view the image.

Why am I getting this error for just some cases and not others? And how should I fix it?

1 Answer

0 votes
by (38.2k points)

Try the below code, this will resolve your issue:

import requests

image_url = ""

img_data = requests.get(image_url).content

with open('image_name.jpg', 'wb') as handler:


And for authorization

from requests.auth import HTTPBasicAuth

img_data = requests.get('image_url', auth=HTTPBasicAuth('user', 'pass')).content

If you wish to Learn more about Python visit this Python Online Training.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !