Python下载百度新歌100的代码

软件和网站开发以及相关技术探讨
yunpengwu
帖子: 294
注册时间: 2007-08-26 10:35
来自: 上海
联系:

#31

帖子 yunpengwu » 2007-10-23 17:35

楼主,我修改了几个html解析的bug:

1。 修改正则表达式匹配
2。修改处理3个和3个以上歌手的匹配

请过目!

只列出主程序:

代码: 全选

if __name__ == "__main__":
    conn = httplib.HTTPConnection('list.mp3.baidu.com')
    conn.request("GET",topid )  #类型
    response = conn.getresponse()
    html=response.read().decode('gbk')
    conn.close()
    expression1='border">(.*)\.</td>'
    expression2='><a href="http://mp3.baidu.com/m(.*)</a>'
    expression3='href="http://mp3.baidu.com/m(.*)</td>'
    listSentence1 = re.findall(expression1, html)   #编号特征
    listSentence2 = re.findall(expression2, html)   #歌曲名特征
    listSentence3 = re.findall(expression3, html)   #歌手名特征

    for lineno in range(len(listSentence1)):
       url=re.search('(.*)target',listSentence2[lineno])
       url='/m'+url.group(0)[:-8]
       idno=listSentence1[lineno]
       name=re.search('blank>(.*)',listSentence2[lineno])
       name=name.group(0)[6:]
       if re.search('<b>(.*)</b>', name) is not None:
           name = name[3:-4]
       # 处理一个或者多个歌手
       sep = re.compile(r'</A>/<A ')
       author_list = sep.split(listSentence3[lineno])
       if len(author_list) == 1:        #独唱
           author=re.search('blank>(.*)</',listSentence3[lineno])
           author=author.group(0)[6:-2]
       else:
           authors = []
           for i in range(len(author_list)-1):
               tmp = re.search('blank>(.*)$', author_list[i])
               authors.append(tmp.group(0)[6:])
           tmp = re.search('blank>(.*)</', author_list[len(author_list)-1])
           authors.append(tmp.group(0)[6:-2])

           author = ''
           for i in authors:
               author += i + '+'
           author = author[:-1]

       name=name.strip()
       author=author.strip()
       print u"开始下载 [",idno, ']', name,author,u"来自",url
       filelist=os.listdir('.');
      # if axeldownmp3(url,author,name,filelist)==0:  #判断失败
       if downmp3(url,author,name,filelist)==0:  #判断失败
          print u"下载",author,name,u'失败!'
头像
gnix_oag
帖子: 1994
注册时间: 2005-05-19 18:38
来自: 湖南永州
联系:

#32

帖子 gnix_oag » 2007-10-23 17:48

大家都用这个下载啊

我可直接在ftp上下载,

一叶不但提供下载脚本,还提供ftp下载,

呵呵。
头像
bones7456
帖子: 8495
注册时间: 2006-04-12 20:05
来自: 杭州
联系:

#33

帖子 bones7456 » 2007-10-23 17:53

gnix_oag 写了:大家都用这个下载啊

我可直接在ftp上下载,

一叶不但提供下载脚本,还提供ftp下载,

呵呵。
你是说我搞的那个?那样同步成问题哦~ :lol:
关注我的blog: ε==3
liyangmin
帖子: 25
注册时间: 2007-10-25 10:08

#34

帖子 liyangmin » 2007-10-30 18:14

赞一下先
honggou027
帖子: 6
注册时间: 2006-08-13 19:15

#35

帖子 honggou027 » 2007-11-02 14:43

发现 http://wma.1ting.com/wmam/quku/1018/ins ... son/11.wma
正在处理 http://220.181.38.82/m?ct=134217728&tn= ... 0&word=wma,
http://wma.hyjy.net//5353/13227/Y2Uz.wma,,
[%D0%D6%B5%DC+%B3%C2%DE%C8%D1%B8%2B%C1%F5%B5%C2%BB%AA]&si=
%D0%D6%B5%DC;;%B3%C2%DE%C8%D1%B8+%C1%F5%B5%C2%BB%AA;;218921;;218921&lm=16777216
('http protocol error', 0, 'got a bad status line', None)
Traceback (most recent call last):
File "mp3.py", line 183, in <module>
if axeldownmp3(url,author,name,filelist)==0: #判断失败
File "mp3.py", line 125, in axeldownmp3
urllists=getdownurl(url) #获取文件url列表
File "mp3.py", line 76, in getdownurl
mp3url=getdownfileurl(listSentence2[lineno]) #转换链接为最终下载地址
File "mp3.py", line 55, in getdownfileurl
url = re.search(expression2, data).group(0)[16:-9]
UnboundLocalError: local variable 'data' referenced before assignment
头像
Darkclouds
帖子: 23
注册时间: 2007-08-31 20:10

#36

帖子 Darkclouds » 2007-11-11 9:12

这个帖子好强。。。。。。
收藏一下
ljdam
帖子: 14
注册时间: 2007-11-30 11:59

#37

帖子 ljdam » 2007-11-30 15:16

这个帖子不顶不行,占位下班回家试试
头像
hellojinjie
帖子: 1150
注册时间: 2007-09-14 21:03
来自: 浙江

#38

帖子 hellojinjie » 2007-12-21 23:34

太强了,我用C写过下载网页再找网页中要的东西写入到文本中,但是失败了,啥时学会了python用她来试试
Say hello to everyday!
hxs_handle
帖子: 9
注册时间: 2008-02-01 10:51

#39

帖子 hxs_handle » 2008-02-01 17:04

呵呵,很不错。
======python 进行中========
lylove122028
帖子: 1
注册时间: 2008-02-07 17:17

真不错

#40

帖子 lylove122028 » 2008-02-08 3:57

如何下载?
头像
百草谷居士
帖子: 3916
注册时间: 2006-02-10 16:36
系统: Mint21.1/Deepin20.8

#41

帖子 百草谷居士 » 2008-02-15 9:52

使用21楼代码,出现如下错误:
开始下载 1 期待你的爱 林俊杰 来自 /m?tn=baidump3&ct=134217728&lm=-1&li=2&word=%C6%DA%B4%FD%C4%E3%B5%C4%B0%AE+%C1%D6%BF%A1%BD%DC%09
获取文件列表
获得 30 个下载地址
尝试 None
Traceback (most recent call last):
File "/home/lpl/下载百度歌曲.py", line 182, in <module>
if axeldownmp3(url,author,name,filelist)==0: #判断失败
File "/home/lpl/下载百度歌曲.py", line 129, in axeldownmp3
ext=urllists[lineno][0][-4:].lower() #获取文件名后缀(最后4位)
TypeError: 'NoneType' object is unsubscriptable
debian 12 / 深度系统 20.9 / Mint 21.3

为何热衷于搞发行版的多,搞应用程序开发的少?Linux最多余的就是各种发行版,最缺的就是应用程序,特别是行业应用程序。
头像
zwssd
帖子: 81
注册时间: 2007-06-10 12:19

#42

帖子 zwssd » 2008-02-15 15:25

开始下载 1 期待你的爱 林俊杰 来自 /m?tn=baidump3&ct=134217728&lm=-1&li=2&word=%C6%DA%B4%FD%C4%E3%B5%C4%B0%AE+%C1%D6%BF%A1%BD%DC%09
获取文件列表
获得 30 个下载地址
尝试 None
Traceback (most recent call last):
File "/home/lpl/下载百度歌曲.py", line 182, in <module>
if axeldownmp3(url,author,name,filelist)==0: #判断失败
File "/home/lpl/下载百度歌曲.py", line 129, in axeldownmp3
ext=urllists[lineno][0][-4:].lower() #获取文件名后缀(最后4位)
TypeError: 'NoneType' object is unsubscriptable
头像
zwssd
帖子: 81
注册时间: 2007-06-10 12:19

#43

帖子 zwssd » 2008-02-16 7:45

将21楼的代码 220.181.38.82 改成: 202.108.23.172 就行了哈
头像
zwssd
帖子: 81
注册时间: 2007-06-10 12:19

#44

帖子 zwssd » 2008-02-16 12:27

修改了点点代码,哈哈。加了个GTK的关于对话框,水平低,别的不会弄(就这还弄个好几个钟头)
说明:点关闭后就可以开始下载了哈

代码: 全选

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2008 UbuntuChina <http://forum.ubuntu.org.cn>
# License: GPLv2
# Author: oneleaf <oneleaf AT gmail.com>
# hack by ct <ctqucl AT gmail.com>
# code modify by david <zwssd190 AT 163.com> 增加了关于对话框

import pygtk
import gtk

import httplib
import re
import urllib
import os
import locale

def startdownload(start):
	print "程序将开始下载工作......"
	global m,topid
	global fsize
	fsize=1     #文件大小下限(M)
	allowext=['.mp3','.wma'] #允许的扩展名
	topid='0'

	if topid=='0':
	     topid='/list/newhits.html'         #新歌100
	elif topid=='1':
	     topid='/topso/mp3topsong.html'     #Top500
	elif topid=='2':
	     topid='/list/oldsong.html'         #老歌经典
	elif topid=='3':
	     topid='/list/movies.html'          #电影金曲
	elif topid=='4':
	     topid='/list/tvs.html'             #电视歌曲
	elif topid=='5':
	     topid='/minge/mp3topsong.html'     #民歌精选
	elif topid=='6':
	     topid='/xiaoyuan/mp3topsong.html'  #校园歌曲
	elif topid=='7':
	     topid='/list/liujinsuiyue.html'    #流金岁月(new)
	elif topid=='8':
	     topid='/list/yaogun.html'          #摇滚地带


	def getdownfileurl(url):                #获取歌曲页的试听URL
	    url = "http://220.181.38.82/m"+url
	    count = url.index('" ');
	    url = url[:count]
	    tn = re.search('&tn=(.*)&word',url).group(0)
	    url=url.replace(tn,'&tn=baidusg,mp3%20%20&word')
	    print u"正在处理",url
	    try:
	        urlopen = urllib.URLopener()
	        fp=urlopen.open(url)
	        data = fp.read()
	        fp.close()
	    except IOError, errmsg:
	        print errmsg
	    expression2='"_blank">(.*)</a></li>'
	    url = re.search(expression2, data).group(0)[16:-9]
	    try:
	        url="http://"+urllib.quote(url)
	    except:pass
	    print u"发现 "+url
	    return url

	def getdownurl(url):                     #从歌曲页抓取URL列表
	    #print url
	    urllist=[]
	    urllist1=[]
	    urllist2=[]
	    conn = httplib.HTTPConnection('mp3.baidu.com')
	    conn.request("GET",url)
	    response = conn.getresponse()
	    html=response.read()
	    conn.close()
	    expression2='http://202.108.23.172/m(.*)target'
	    listSentence2 = re.findall(expression2, html)     #抓取链接列表
	    #print u"|||||||||||",listSentence2,"!!!!!!!!!"
	    filesize=re.findall('<td>(.*)M</td>',html)        #抓取文件大小
	    lineno=0
	    while lineno<len(listSentence2):
	        #print listSentence2[lineno],"开始转换链接为最终下载地址......"
	        mp3url=getdownfileurl(listSentence2[lineno])  #转换链接为最终下载地址
	        if mp3url:
	            urllist1.append(mp3url)
	        else:
	            urllist1.append('')
	        lineno+=1
	    urllist=map(None,urllist1,filesize)
	    return urllist

	def downmp3(url,author,name,filelist):    #下载歌曲
	    filename=author+"-"+name;
	    for i in filelist:
	        name=unicode(i,locale.getpreferredencoding())
	        if name.find(filename) == 0:      #忽略
	            print u"文件已经下载,忽略。"
	            return 1
	    urllists=getdownurl(url)              #获取文件url列表
	    lineno=0
	    while lineno<len(urllists):
	        print u"尝试",urllists[lineno][0]
	        ext=urllists[lineno][0][-4:]      #获取文件名后缀(最后4位)
	        try:
	            lineno+=1
	            print urllists[lineno-1][1] +'M'
	            if float(urllists[lineno-1][1])>float(fsize) :   #大小符合则下载
	                  urlopen = urllib.URLopener()
	                  fp=urlopen.open(urllists[lineno-1][0])
	                  data = fp.read()
	                  fp.close()
	                  filename=filename+ext;
	                  file=open(filename,'w+b')
	                  file.write(data)
	                  file.close()
	                  print u"下载成功!"
	                  return 1
	            elif float(urllists[lineno][1])<float(fsize) :   #不符则略过
	                  print u"文件太小,忽略!"
	        except:
	            continue
	    return 0

	def axeldownmp3(url,author,name,filelist):    #使用axel下载歌曲,Ubuntu用户需要使用 sudo apt-get install axel安装.
	    filename=author+"-"+name;
	    for i in filelist:
	        name=unicode(i,locale.getpreferredencoding())
	        if name.find(filename) >= 0:      #忽略
	            print u"%s 文件已经下载,忽略。"%filename
	            return 1
	    print u'获取文件列表'
	    urllists=getdownurl(url)              #获取文件url列表
	    lineno=0
	    print u"获得",len(urllists),"个下载地址"
	    while lineno<len(urllists):
	        print u"尝试",urllists[lineno][0]
	        #print urllists
	        ext=urllists[lineno][0][-4:].lower()      #获取文件名后缀(最后4位)
	        if not ext in allowext:
	            print u"文件扩展名 %s 名不允许,忽略"%ext
	            lineno+=1
	            continue
	        try:
	            lineno+=1
	            print urllists[lineno-1][1] +'M'
	            if float(urllists[lineno-1][1])>float(fsize) :   #大小符合则下载
	                  savefilename=filename+ext;
	                  if os.spawnlp(os.P_WAIT,'axel','-q','-n 20','-o '+savefilename,urllists[lineno-1][0])==0:
	                          print u"下载成功!"
	                          return 1
	            elif float(urllists[lineno][1])<float(fsize) :   #不符则略过
	                  print u"文件太小,忽略!"
	        except:
	            continue
	    return 0

	if __name__ == "__main__":
	    conn = httplib.HTTPConnection('list.mp3.baidu.com')
	    conn.request("GET",topid )  #类型
	    response = conn.getresponse()
	    html=response.read().decode('gbk')
	    conn.close()
	    expression1='border">(.*).</td>'
	    expression2='><a href="http://mp3.baidu.com/m(.*)</a>'
	    expression3='href="http://mp3.baidu.com/m(.*)</td>'
	    listSentence1 = re.findall(expression1, html)   #编号特征
	    listSentence2 = re.findall(expression2, html)   #歌曲名特征
	    listSentence3 = re.findall(expression3, html)   #歌手名特征
	    lineno=0
	    while lineno<len(listSentence1):
	       url=re.search('(.*)target',listSentence2[lineno])
	       url='/m'+url.group(0)[:-8]
	       idno=listSentence1[lineno]
	       name=re.search('blank>(.*)',listSentence2[lineno])
	       name=name.group(0)[6:]
	       dirty=re.search('</A>/<A  href=(.*) target=_blank>',listSentence3[lineno])
	       if dirty is not None :             #合唱
	           author1=re.search('>(.*)</A>/<A',listSentence3[lineno])
	           author1=author1.group(0)[1:-7]
	           author2=re.search('/<A  href=(.*)</A>',listSentence3[lineno])
	           author2=re.search('>(.*)<',author2.group(0))
	           author2=author2.group(0)[1:-1]
	           author=author1 + '+' + author2
	       elif dirty is None :               #独唱
	           author=re.search('blank>(.*)</',listSentence3[lineno])
	           author=author.group(0)[6:-2]
	       name=name.strip()
	       author=author.strip()
	       print u"开始下载",idno,name,author,u"来自",url
	       filelist=os.listdir('.');
	       if axeldownmp3(url,author,name,filelist)==0:  #判断失败
	          print u"下载",author,name,u'失败!'
	       lineno+=1

class baidump3:
    __license__ = """
baidump3下载器 1.0.0 for python
请保留作者的名字的前题下,随便改,随便发布!哈哈
"""
    __authors__ = ["""
Author: oneleaf <oneleaf AT gmail.com>
hack by ct <ctqucl AT gmail.com>
code modify by david <zwssd1980 AT 163.com> 
增加了关于对话框
"""]

    def __init__(self):
        self.window = gtk.Window()

        self.about_dialog = gtk.AboutDialog()
        self.about_dialog.set_name("baidump3下载器")
        self.about_dialog.set_version("1.0.0")
        self.about_dialog.set_license(self.__license__)
        self.about_dialog.set_authors(self.__authors__)
        self.about_dialog.connect("response", self.aboutDialogHide)
        self.about_dialog.show()
        self.about_dialog.connect("destroy",self.kill)

    def kill(self, event):
            gtk.main_quit()
            print "程序已经退出!"

    def main(self):
        gtk.main()

    def aboutDialogHide(self, widget, event):
        self.about_dialog.hide()
        j = 0
        i = 0
        while i<1000:
            j+=i
            i+=1
        startdownload("start")

baidump3().main()
tongttt
帖子: 444
注册时间: 2007-11-27 22:20

#45

帖子 tongttt » 2008-02-19 0:00

不懂得怎么用阿,大家帮帮菜鸟吧
回复