dl.py 759 B

12345678910111213141516171819202122232425262728293031
  1. import os
  2. import urllib
  3. import urllib.error
  4. import urllib.request
  5. from urllib.parse import urlparse, quote, unquote
  6. from http.client import RemoteDisconnected
  7. def encodeUrl(url):
  8. parsed = urlparse(url)
  9. parsed = parsed._replace(path=quote(unquote(parsed.path)),
  10. query=quote(unquote(parsed.query)))
  11. return parsed.geturl()
  12. def downloadFile(url, outputFile):
  13. url = encodeUrl(url)
  14. # Create needed dirs
  15. outputDir = os.path.dirname(outputFile)
  16. if not os.path.isdir(outputDir):
  17. os.makedirs(outputDir)
  18. # Download ..
  19. try:
  20. urllib.request.urlretrieve(url, outputFile)
  21. except (urllib.error.ContentTooShortError, urllib.error.URLError, RemoteDisconnected) as e:
  22. print(e, url)
  23. return str(e)
  24. return None