#!/usr/bin/python
"""
dnld-imgs: download images from url to the current directory

Usage:  dnld-imgs  <url>
"""

import time, urllib, os, sys
from HTMLParser import HTMLParser
from urlparse import *

fmt='%Y-%m-%d_%H-%M-%S'

class ImgLister(HTMLParser):
    def reset(self):
        self.imgs = []
        HTMLParser.reset(self)

    def handle_starttag(self, tag,  attrs):
        if tag == 'img':
            src = [v for k, v in attrs if k=='src']
            if src:
                self.imgs.extend(src)

    def handle_startendtag(self, tag,  attrs):
        if tag == 'img':
            src = [v for k, v in attrs if k=='src']
            if src:
                self.imgs.extend(src)


def list_images(url):
    conn = urllib.urlopen(url)
    encoding = conn.headers.getparam('charset')
    html = conn.read().decode(encoding)
    conn.close()
    p = ImgLister()
    p.feed(html)
    p.close()
    return [urljoin(url,i,False) for i in p.imgs]

def download_images(url):
    imgs = list_images(url)
    for i in imgs:
        name = time.strftime(fmt)+'_'+os.path.split(urlsplit(i).path)[-1]
        data = urllib.urlopen(i).read()
        open(name,'w').write(data)



if __name__ == '__main__':
    url = sys.argv[1]
    try:
        download_images(url)
        sys.exit(0)
    except:
        print __doc__
        sys.exit(1)