python抓取网页之下载音乐

  实现个爬虫小例子,用浏览器登录百度帐号后,不要退出。

运行如下代码:

 1 # -*- coding: utf-8 -*-
 2 import re,sys
 3 import urllib,urllib2,cookielib
 4 class Requests:
 5     def __init__(self):     
 6         cj = cookielib.CookieJar()
 7         opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
 8         urllib2.install_opener(opener)
 9         self.src=None
10         self.content=None
11     def get(self,url):
12         self.src=urllib2.urlopen(url)
13         self.content=self.src.read()
14         self.src.close()
15         return self.content
16     
17 def getMusic(v,num):
18     var={'top':'song'}               #现在仅支持获取榜单音乐
19     s=Requests()
20     body=s.get("http://music.baidu.com/"+v)
21 
22     ids=re.findall("href=\"/"+var[v]+"/\d+",body)
23     if not ids:
24         sys.exit(-1)
25     idlists=[]
26     fg=len("href=\"/"+var[v])+1
27     for i in ids:
28         idlists.append(i[fg:])      
29     if num>len(idlists):
30         num=len(idlists)
31     for songId in idlists[0:num]:
32         body=s.get("http://music.baidu.com/"+var[v]+"/"+songId)      
33         if not body:
34             print songId,": no response."
35             return -1;
36         #print body
37 
38         name=re.search("<title>\S*,",body)
39         if not name:
40             print "no name"
41             return -1;
42         strname=name.group()
43         name=strname.split(',')[0][7:]
44         print name,
45         
46         fd=open(name+".mp3","wb+")
47         gs=re.findall("http://\S+xcode\S+",body)
48         if gs:
49             for i in gs:
50                 url=i[0:len(i)-1]
51                 mp3=s.get(url)
52                 fd.write(mp3)
53                 print "成功!"
54         else:
55             print "失败!"
56         fd.close()
57 if __name__=='__main__':
58     getMusic('top',2)          #获取2首

会在你的代码文件当前目录下创建下载的音乐。

解析html仅用的re模块,倒是可以用HTMLParser等模块,这里比较简单就没用。

posted @ 2013-10-20 18:33  除e尘  阅读(2035)  评论(1编辑  收藏  举报