Anders Breid
Anders Breid

Reputation: 141

How to download file using Python and authentication

I am trying to download a .tar file through a link not directly to the file. If you browse to the page a popup appears with "Select path to download"

the url looks like this: http://document.internal.somecompany.com/Download?DocNo=2/1449-CUF10101/1

I am new to python.

This is my code so far with this part of the project:

manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, url, secrets["user"], secrets["password"])

#Create an authentication handler using the password manager
auth = urllib2.HTTPBasicAuthHandler(manager)

#Create an opener that will replace the default urlopen method on further calls
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)

#Here you should access the full url you wanted to open
response = urllib2.urlopen(url)
print response

Printing the response return this: <addinfourl at 139931044873856 whose fp = <socket._fileobject object at 0x7f443c35e8d0>>

I do not know how to go further, or if the response is anything near correct? I need to open the .tar and access a raml-file in it, and I do not know if I need to download the file and open it or just open it directly and print out the raml-file.

Any suggestions?

Upvotes: 1

Views: 925

Answers (1)

Mohd
Mohd

Reputation: 5613

You need to open a file in 'wb' mode and write the content of the file you are trying to download, as the following:

response = urllib2.urlopen(url)
with open(os.path.basename(url), 'wb') as wf:
            wf.write(response.read())

You can also specify the path instead of using just os.path.basename(url) and have a look at tarfile for more info on how to deal with .tar files

Upvotes: 1

Related Questions