Skip to content

Instantly share code, notes, and snippets.

@bigeagle
Created February 6, 2012 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bigeagle/1749948 to your computer and use it in GitHub Desktop.
Save bigeagle/1749948 to your computer and use it in GitHub Desktop.
fetch album cover from douban
#!/usr/bin/python2
# -*- encoding:utf8 -*-
import os
import urllib
import urllib2
import time
import re
import eyeD3
import argparse
urlread = lambda url: urllib2.urlopen(url).read()
class getAlbumCover:
_doubanSearchApi = 'http://www.douban.com/search?search_text={0}'
_doubanCoverPattern = '<img src="http://img[0-9].douban.com/spic/s(\d+).jpg"'
_doubanConverAddr = 'http://img3.douban.com/lpic/s{0}.jpg'
_eyeD3 = None
imgpath = os.getenv("HOME") + "/.covers/"
def fetch_cover(self):
keywords = self.artist + ' ' + ( self.album or self.title )
searchstring = urllib2.quote(keywords)
if not os.path.exists(self.cover):
url = self._doubanSearchApi.format(searchstring)
#print url
header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 (FoxPlus) Firefox/2.0.0.14'}
request = urllib2.Request(url, headers=header )
result = urlread(request)
match = re.compile(self._doubanCoverPattern, re.IGNORECASE).search(result)
if match:
image = self._doubanConverAddr.format(match.groups()[0])
print "下载封面"
urllib.urlretrieve(image, self.cover)
time.sleep(2)
else:
raise Exception
def __init__(self, mp3):
self._eyeD3 = eyeD3.Tag()
try:
self._eyeD3.link(mp3)
self.getFileInfo()
except:
print "读取文件错误!"
def getFileInfo(self):
''' 获取专辑信息 '''
self.artist = self._eyeD3.getArtist().encode('utf-8')
self.album = self._eyeD3.getAlbum().encode('utf-8')
self.title = self._eyeD3.getTitle().encode('utf-8')
self.cover = self.imgpath + self.artist + '-' + self.album + '.jpg'
def updateCover(self):
'''更新专辑封面至文件'''
try:
self._eyeD3.removeImages()
self._eyeD3.addImage(3,self.cover, u'')
self._eyeD3.update()
print "更新专辑封面成功"
return True
except:
print '修改文件错误'
return False
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download MP3 album cover from douban.")
parser.add_argument( '-i', '--update', action='store_true', help="Write album cover into id3 tags" )
parser.add_argument( 'mp3', nargs='+', help="MP3 filename" )
args = parser.parse_args()
for i in args.mp3:
if re.search('.mp3$',i):
print "正在处理", i
handler = getAlbumCover(i)
if handler.artist and ( handler.album or handler.title ):
try:
handler.fetch_cover()
if args.update:
handler.updateCover()
except :
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment