| OLD | NEW |
| (Empty) | |
| 1 #!/usr/bin/python |
| 2 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 3 # Use of this source code is governed by a BSD-style license that can be |
| 4 # found in the LICENSE file. |
| 5 |
| 6 """Download all files and directories from a URL. |
| 7 |
| 8 Provided a URL, this script will download files and folders with 'href' |
| 9 attribute as the name and the URL as the base path. |
| 10 |
| 11 This was only tested on Apache web directory. |
| 12 """ |
| 13 |
| 14 import optparse |
| 15 import os |
| 16 import re |
| 17 import sys |
| 18 import urllib |
| 19 import urllib2 |
| 20 |
| 21 |
| 22 def IsFile(url): |
| 23 """Check if URL is a file type. |
| 24 |
| 25 If 'Etag' is in the header response, it must be a file type. |
| 26 """ |
| 27 try: |
| 28 response = urllib2.urlopen(url) |
| 29 if 'Etag' in response.info(): |
| 30 return True |
| 31 except urllib2.URLError: |
| 32 pass |
| 33 return False |
| 34 |
| 35 |
| 36 def Download(base_url, target): |
| 37 """Recursively download files and directories. |
| 38 |
| 39 Returns: |
| 40 True if succeeded downloading all items, false otherwise. |
| 41 """ |
| 42 # Get list of files in this url path. |
| 43 try: |
| 44 response = urllib2.urlopen(base_url) |
| 45 except urllib2.URLError: |
| 46 print 'URL does not exist : ' + base_url |
| 47 return False |
| 48 html = response.read() |
| 49 item_list = re.findall(r'href="([^"]*)"', html) |
| 50 |
| 51 # Download all files. |
| 52 for item in item_list: |
| 53 if item.startswith('/'): |
| 54 continue |
| 55 url = base_url + item |
| 56 if item.endswith('/'): |
| 57 dest = os.path.join(target, urllib.unquote(item)) |
| 58 if not os.path.isdir(dest): |
| 59 os.makedirs(dest) |
| 60 os.chmod(dest, 0755) |
| 61 if not Download(url, dest): |
| 62 return False |
| 63 elif IsFile(url): |
| 64 dest = os.path.join(target, urllib.unquote(item)) |
| 65 print 'Downloading %s to %s' % (url, dest) |
| 66 urllib.urlretrieve(url, dest) |
| 67 os.chmod(dest, 0755) |
| 68 return True |
| 69 |
| 70 |
| 71 def main(): |
| 72 """Download files from |url| to |target_dir|.""" |
| 73 option_parser = optparse.OptionParser() |
| 74 |
| 75 option_parser.add_option('--url', |
| 76 help='Base URL to the files.') |
| 77 target_dir = os.getcwd() |
| 78 option_parser.add_option('--target-dir', default=target_dir, |
| 79 help='Target path to put the downloaded files.') |
| 80 options, _ = option_parser.parse_args() |
| 81 |
| 82 if not options.url: |
| 83 print 'No url provided.' |
| 84 return 1 |
| 85 base_url = options.url |
| 86 if not base_url.endswith('/'): |
| 87 base_url += '/' |
| 88 |
| 89 if not os.path.isdir(options.target_dir): |
| 90 os.makedirs(options.target_dir) |
| 91 os.chmod(options.target_dir, 0755) |
| 92 |
| 93 success = Download(base_url, options.target_dir) |
| 94 if success: |
| 95 return 0 |
| 96 return 1 |
| 97 |
| 98 |
| 99 if '__main__' == __name__: |
| 100 sys.exit(main()) |
| OLD | NEW |