]> gitweb.pimeys.fr Git - scripts-20-100.git/blob - download_picasa_album.py
Pour télécharger un album Picasa
[scripts-20-100.git] / download_picasa_album.py
1 #!/usr/bin/env python
2 # -*- encoding:utf-8 -*-
3
4 """
5
6 Pour télécharger un album Picasa sans avoir à utiliser l'application Picasa
7
8 Il faut lui fournir le l'url vers le flux RSS
9
10 """
11
12 import urllib
13 import lxml.etree
14 import os
15
16 def get_album(url):
17 """Récupère le xml décrivant l'album à partir de l'``url`` du flux RSS"""
18 page = urllib.urlopen(url)
19 content = page.read()
20 parsed = lxml.etree.fromstring(content)
21 return parsed
22
23 def album_to_links(album):
24 """Un peu de xpath pour récupérer les liens directs des éléments
25 de l'``album``."""
26 medias = album.xpath("//media:group", namespaces=album.nsmap)
27 processed = []
28 for media in medias:
29 contenturls = media.xpath("./media:content", namespaces=media.nsmap)
30 # Pour les photos il n'y a qu'un seul media:content
31 # Mais pour la vidéo, il y a un thumbnail avant
32 if len(contenturls) > 1:
33 contenturl = contenturls[1]
34 else:
35 contenturl = contenturls[0]
36 contenturl = [val for (kw, val) in contenturl.items() if kw == "url"][0]
37 title = media.xpath("./media:title", namespaces=media.nsmap)[0]
38 title = title.text
39 processed.append([title, contenturl])
40 return processed
41
42 def download_file(url, path):
43 """Télécharge le fichier depuis l'``url`` et l'enregistre dans ``path``."""
44 page = urllib.urlopen(url)
45 with open(path, "w") as f:
46 bloc = page.read(4096)
47 while bloc != "":
48 f.write(bloc)
49 bloc = page.read(4096)
50
51 def do_all(rss_url, folder):
52 """Télécharge tout l'album depuis ``rss_url`` et le stocke dans ``folder``"""
53 album = get_album(rss_url)
54 titles = album.xpath("//image/title", namespaces=album.nsmap)
55 albumtitle = titles[0].text
56 os.mkdir("%s/%s" % (folder, albumtitle))
57 linktitles = album_to_links(album)
58 for [title, url] in linktitles:
59 print "Downloading %s : %s" % (title, url)
60 download_file(url, "%s/%s/%s" % (folder, albumtitle, title))
61 return albumtitle
62
63 if __name__ == "__main__":
64 import sys
65 rss_url = sys.argv[1]
66 albumtitle = do_all(rss_url, ".")
67 print (u"Téléchargé dans %s" % albumtitle).encode("utf-8")