#################################################################################################
#################################################################################################
# Following are the most commonly used calls for downloading files in python:
# It depends on version, (2 vs 3) or whether we use standard library (urllib) or
# external modules (wget, requests)
# Using urllib
urllib.urlretrieve ('url_to_file', file_name)
# Using urllib2
urllib2.urlopen('url_to_file')
# Using requests library
requests.get(url)
# Using wget library
wget.download('url', file_name)
#Note: urlopen and urlretrieve are found to perform relatively bad with downloading large files
#(size > 500 MB). requests.get stores the file in-memory until download is complete.
#Note2: Most of these methods will store the contents in a variable, and then we ll need to iterate
# over it and write it to a file, in text mode, or binary mode. See below.
#################################################################################################
#################################################################################################
# Using urllib2
# Basics
#In Python 2, use urllib2 which comes with the standard library.
# Ex 1.
# import module
import urllib2
# store url response in variable response
response = urllib2.urlopen('http://www.example.com/')
# call method .read() on response and store in html
html = response.read()
# Ex 2 - + Saving to File
#The wb in open('test.mp3','wb') opens a file (and erases any existing file)
#in binary mode so you can save data with it instead of just text.
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
# Writing to file
with open('test.mp3','wb') as output:
output.write(mp3file.read())
# Ex 3 - Saving to file, Parsing Filename, Reading by buffer
import urllib2
import os
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1] # parse filename
u = urllib2.urlopen(url) # open url, store in u
f = open(file_name, 'wb') # open filename, for writing
meta = u.info() # print meta information, using info()
file_size = int(meta.getheaders("Content-Length")[0]) # get the size of the file
print "Downloading: %s Bytes: %s" % (file_name, file_size)
os.system('cls')
file_size_dl = 0 # set starting file size
block_sz = 8192 # set starting block size
while True:
buffer = u.read(block_sz) # read the first block
if not buffer:
break
file_size_dl += len(buffer) # update file size
f.write(buffer) # write block into output file
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
# Ex. 4 - with functions for download
import os
from urllib2 import urlopen, URLError, HTTPError
def dlfile(url):
# Open the url
try:
f = urlopen(url)
print "downloading " + url
# Open our local file for writing
with open(os.path.basename(url), "wb") as local_file:
local_file.write(f.read())
#handle errors
except HTTPError, e:
print "HTTP Error:", e.code, url
except URLError, e:
print "URL Error:", e.reason, url
def main():
# Iterate over image ranges
for index in range(150, 151):
url = ("http://www.archive.org/download/"
"Cory_Doctorow_Podcast_%d/"
"Cory_Doctorow_Podcast_%d_64kb_mp3.zip" %
(index, index))
dlfile(url)
if __name__ == '__main__':
main()
# Ex 5 - with progress bar
import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
#################################################################################################
#################################################################################################
# Using urllib
# urllib has method irlretrieve, which will save the file in first parameter, to the pathname in
# second, ie :
# Python 2
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
#(for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve)
import urllib.request
import urllib.request.urlretrieve
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
# Ex Basic (Using urllib - Most stable method)
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
# Ex.1 (Python 3 + only standard lib)
# Read the html response
urllib.request.urlopen
import urllib.request
response = urllib.request.urlopen('http://www.example.com/')
html = response.read()
# Retrieve / Download file
urllib.request.urlretrieve
import urllib.request
urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
# Ex. 2 (Python 2 + print)
import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()
sock.close()
print htmlSource
# Ex. 3 (Python 3 + output to file)
#urlretrieve and requests.get is simple, however in reality not.
#I have fetched data for couple sites, including text and images,
#the above two probably solve most of the tasks. but for a more
#universal solution I suggest the use of urlopen. As it is included
#in Python 3 standard library, your code could run on any machine that
#run Python 3 without pre-installing site-par
# Note:
#This answer provides a solution to HTTP 403 Forbidden when downloading
#file over http using Python. I have tried only requests and urllib
#modules, the other module may provide something better, but this is
#the one I used to solve most of the problems.
import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)
len_content = url_content.length
#remember to open file in bytes mode
with open(filename, 'wb') as f:
while True:
buffer = url_connect.read(buffer_size)
if not buffer: break
#an integer value of size of written data
data_wrote = f.write(buffer)
#you could probably use with-open-as manner
url_connect.close()
# Ex. 4 (Python 2 + two ways to do read()
# Note :
# urllib2 is more complete than urllib and should likely be the module
# used if you want to do more complex things, but to make the answers
#more complete, urllib is a simpler module if you want just the basics:
import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()
Will work fine. Or, if you don't want to deal with the "response" object you can call read() directly:
import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
# Ex. 5 (Python 3 + Using .decode method for binary)
import urllib.request
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read() # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary
# Ex. 6 (Python3 + urlretrieve()) - urlretrieve is considered deprecated
# The easiest way to download and save a file is to use the urllib.request.urlretrieve function:
import urllib.request
# Download the file from `url` and save it locally under `file_name`:
urllib.request.urlretrieve(url, file_name)
# Ex. 7 (Python3 + urlretrieve + get filename)
# Download the file from `url`, save it in a temporary directory and get the
# path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
file_name, headers = urllib.request.urlretrieve(url)
#But keep in mind that urlretrieve is considered legacy and might become
#deprecated (not sure why, though).
# Ex. 8 (Python 3 - Most correct way - using urlopen())
#But this works well only for small files.
import urllib.request
import shutil
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
# Ex. 9 ( Python 3 - Using .write())
# If this seems too complicated, you may want to go simpler and store the whole #download in a bytes
# object and then write it to a file.
import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
data = response.read() # a `bytes` object
out_file.write(data)
# Ex .10 (Combined with unzipping)
#It is possible to extract .gz (and maybe other formats) compressed data on
#the fly, but such an operation probably requires the HTTP server to support
#random access to the file.
import urllib.request
import gzip
...
# Read the first 64 bytes of the file inside the .gz archive located at `url`
url = 'http://example.com/something.gz'
with urllib.request.urlopen(url) as response:
with gzip.GzipFile(fileobj=response) as uncompressed:
file_header = uncompressed.read(64) # a `bytes` object
# Or do anything shown above using `uncompressed` instead of `response
#################################################################################################
#################################################################################################
# Using requests
# Ex 1 - Using requests module to print length of file
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
r = requests.get(url)
print len(r.content)
#10485760
# Ex 2 - Using method .text
# Note: Used in case of downloading text files
# response.text return the output as a string object,
#use it when you're downloading a text file. Such as HTML file, etc.
import requests
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
with open('/tmp/metadata.pdf', 'wb') as f:
f.write(response.text)
# Ex 3 - Using method .content
# response.content return the output as bytes object, use it when
#you're downloading a binary file. Such as PDF file, audio file, image, etc.
# In case of downloading non text files, here
# response.txt returns a byte string
import requests
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
with open('/tmp/metadata.pdf', 'wb') as f:
f.write(response.content)
# Ex 4 - Using method response.raw
#chunk_size is the chunk size which you want to use. If you set it as 2000,
#then requests will download that file the first 2000 bytes, write them into
#the file, and do this again, again and again, unless it finished.
#So this can save your RAM. But I'd prefer use response.content instead in
#this case since your file is small. As you can see use response.raw is complex.
import requests
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
r = requests.get(url, stream=True)
with open('/tmp/metadata.pdf', 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
# Ex 5 - Using requests module + implemented progressbar + tqdm
from tqdm import tqdm
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
#################################################################################################
#################################################################################################
# Using wget
import wget
wget.download('url')
#If you have wget installed, you can use parallel_sync.
#pip install parallel_sync
from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)