-1

I've seen many solutions to manage authentication and download an image from a website, but I'm a little bit lost among all of these libraries:

  • urllib
  • urllib2
  • pycurl
  • requests
  • other dark solutions I didn't understand...

Basically, I want to retrieve an image from a website which requires authentication. What is the simplest way to do it in python-2.7 ?

Thank you.

RomainTT
  • 140
  • 5

2 Answers2

0

You can have a look to the requests doc. For example, if you need basic HTTP authentication:

requests.get('http://example.com/image.png', auth=HTTPBasicAuth('user', 'pass'))
cyprieng
  • 706
  • 6
  • 16
0

I finally managed to do it with requests only.

import requests

url_login = ''
url_image = ''

username = ''
password = ''

# Start a session so we can have persistant cookies
session = requests.session()

# This is the form data that the page sends when logging in
login_data = {
    'login': username,
    'password': password,
    'submit': 'Login'
}

# Authenticate
r = session.post(url_login, data=login_data)

# Download image
with open('output.png', 'wb') as handle:
    response = session.get(url_image, stream=True)

    if not response.ok:
        print "Something went wrong"
        return False

    for block in response.iter_content(1024):
        handle.write(block)

    handle.close()
RomainTT
  • 140
  • 5