6

My file named as 'blueberry.jpg' begins downloading, when I click on the following url manually provided that the username and password are typed when asked: http://example.com/blueberry/download

How can I make that happen using Python?

import urllib.request

url = 'http://example.com/blueberry/download'

data = urllib.request.urlopen(url).read()

fo = open('E:\\quail\\' + url.split('/')[1] + '.jpg', 'w')
print (data, file = fo)

fo.close()

However above program does not write the required file, how can I provide the required username and password?

12

2 Answers 2

7

Use requests, which provides a friendlier interface to the various url libraries in Python:

import os
import requests

from urlparse import urlparse

username = 'foo'
password = 'sekret'

url = 'http://example.com/blueberry/download/somefile.jpg'
filename = os.path.basename(urlparse(url).path)

r = requests.get(url, auth=(username,password))

if r.status_code == 200:
   with open(filename, 'wb') as out:
      for bits in r.iter_content():
          out.write(bits)

UPDATE: For Python3 get urlparse with: from urllib.parse import urlparse

Sign up to request clarification or add additional context in comments.

5 Comments

got TypeError: 'str' does not support the buffer interface
for python 3, i am using the code as 'code' fo = open(filename, 'wb') for bits in r.iter_content(): print (bits, file = fo) fo.close()
in python 2.7 it wrote a file but not the required jpg file because the known url is only 'example.com/blueberry/download'
Simply replace filename with whatever you want the filename to be.
For Python3 get urlparse with: from urllib.parse import urlparse
-1

I'm willing to bet you are using basic auth. So try doing the following:

import urllib.request

url = 'http://username:[email protected]/blueberry/download'

data = urllib.request.urlopen(url).read()

fo = open('E:\\quail\\' + url.split('/')[1] + '.jpg', 'w')
print (data, file = fo)

fo.close()

Let me know if this works.

3 Comments

i got the error perhaps my password is combination of special characters like $/_. The error message tells:http.client.InvalidURL: nonnumeric port:
As much as the solution i provided is simple - @Burhan Khalid's is much better. It can handle potential error messages in a clean way.
urlopen does not appear to parse any username and password in front of the hostname like http://user:[email protected] - it sees the colon between user:pwd and attempts to parse out a port.

Your Answer

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