Back

Explore Courses Blog Tutorials Interview Questions
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:

        f.write(r.content)

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 (41.4k 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:

    handler.write(img_data)

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.

Related questions

0 votes
1 answer
asked Nov 12, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 12, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 12, 2020 in Python by ashely (50.2k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...