Comment télécharger un fichier (pdf, text,...) du web à partir de l'url en python ?

Published: 23 juillet 2014

DMCA.com Protection Status

Pour télécharger un fichier pdf du web à partir de son url en python il existe le module urllib et la fonction urlretrieve. Soit par exemple le fichier pdf en ligne suivant:

http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf

En utilisant python 3

>>> import urllib.request
>>> urllib.request.urlretrieve('http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf', "st-intro.pdf")

En utilisant python 2

Pour télécharger on peut alors faire comme ceci:

>>> import urllib
>>> urllib.urlretrieve('http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf', "st-intro.pdf")

Note: on peut aussi changer le nom du fichier en le téléchargeant (exemple: 'new_file.pdf'):

>>> urllib.urlretrieve('http://math.univ-toulouse.fr/~besse/Wikistat/pdf/st-intro.pdf', "new_file.pdf")

Références