Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download file using Python? [duplicate]

I'm completely new to Python, I want to download a file by sending a request to the server. When I type it into my browser, I see the CSV file is downloaded, but when I try sending a get request it does not return anything. for example:

import urllib2
response = urllib2.urlopen('https://publicwww.com/websites/%22google.com%22/?export=csv')
data = response.read()
print 'data: ',  data

It does not show anything, how can I handle that? When I search on the web, all the questions are about how to send a get request. I can send the get request, but I have no idea of how the file can be downloaded as it is not in the response of the request.

I do not have any idea of how to find a solution for that.

like image 852
Alex Avatar asked Mar 05 '18 15:03

Alex


People also ask

How to download files in Python 2?

We've included it here due to is popularity in Python 2. Another way to download files in Python is via the urllib2 module. The urlopen method of the urllib2 module returns an object that contains file data. To read the contents of Note that in Python 3, urllib2 was merged in to urllib as urllib.request and urllib.error.

How to download website code using Python?

Retrieving website code (CSS, JS, etc) So guys there are many ways to download files using python. Let’s see them one by one. Using requests module is one of the most popular way to download file. So first of all you need to install requests module, so run the following command on your terminal.

How to download the file contents in binary format in Python?

get ( ) method of the requests module is used to download the file contents in binary format. Now you have to open that filename in write binary (wb) mode. output_file.write (r.content) means whatever the url contains, it will get all those contents and it will write all those to output_file. Finally print Download Completed.

How to download a file using Wget in Python?

Using the wget Module. One of the simplest way to download files in Python is via wget module, which doesn't require you to open the destination file. The download method of the wget module downloads files in just one line. The method accepts two parameters: the URL path of the file to download and local path where the file is to be stored.


2 Answers

You can use the urlretrieve to download the file

EX:

u = "https://publicwww.com/websites/%22google.com%22/?export=csv"

import urllib
urllib.request.urlretrieve (u, "Ktest.csv")
like image 50
Rakesh Avatar answered Sep 21 '22 12:09

Rakesh


You can also download a file using requests module in python.

import shutil

import requests

url = "https://publicwww.com/websites/%22google.com%22/?export=csv"
response = requests.get(url, stream=True)
with open('file.csv', 'wb') as out_file:
    shutil.copyfileobj(response.raw, out_file)
del response
like image 36
bigbounty Avatar answered Sep 22 '22 12:09

bigbounty