Python爬虫实践:从中文歌词库抓取歌词
来源:互联网 发布:考勤工资软件 编辑:程序博客网 时间:2024/05/21 22:25
利用BeautifulSoup库构建一个简单的网络爬虫,从中文歌词库网站抓取凤凰传奇所有曲目的歌词(http://www.cnlyric.com/geshou/1927.html)。
from urllib.request import urlopenfrom bs4 import BeautifulSoupimport reimport numpyimport csvstarturl="http://www.cnlyric.com/geshou/1927.html" # 凤凰传奇歌词地址第一页# 找出下一页的链接def findnextlinks(starturl,nextlinks): """ 该函数用于从starturl页面开始,递归找出所有“下一页”的链接地址 要求nextlinks为一个空的列表""" try: html=urlopen(starturl) bsobj=BeautifulSoup(html,"lxml") nextpagelink=bsobj.find("div",{"class":"PageList"}).input.\ previous_sibling.previous_sibling.attrs["href"] nextlink="http://www.cnlyric.com/geshou/"+nextpagelink nextlinks.append(nextlink) findnextlinks(nextlink,nextlinks) except: print("\n所有“下一页”的链接寻找完毕") return nextlinksnextlinks=[]nextlinks=findnextlinks(starturl,nextlinks) # 所有“下一页”的链接列表# 找出存放歌词的链接列表def findlrclinks(urllists): """ 该函数用于找出列表urllists中的链接页面上存放歌词的链接 """ Sites=[] for urllist in urllists: html=urlopen(urllist) bsobj=BeautifulSoup(html,"lxml") for link in bsobj.findAll(href=re.compile("^(../LrcXML/)")): site="http://www.cnlyric.com"+link.attrs["href"].lstrip("..") Sites.append(site) return Sitesnextlinks.insert(0,starturl) # 将开始页面也加入链接列表中Sites=findlrclinks(nextlinks) # 找出所有存放歌词的链接print("\n所有曲目歌词所在的xml文件链接寻找完毕")def getlrc(lrclink): """ 该函数用于找出歌词链接lrclink中的歌词,并以列表形式保存 """ LRC=[] html=urlopen(lrclink) bsobj=BeautifulSoup(html,"lxml") lrcpre=bsobj.findAll("lrc") for lrclabel in lrcpre: lrc=lrclabel.get_text() LRC.append(lrc) return LRCcsvfile=open("凤凰传奇歌词集.csv","w+") # 创建csv文件用于保存数据try: writer=csv.writer(csvfile) rowindex=1 for lrcurl in Sites: LRC=getlrc(lrcurl) LRC.insert(0,str(rowindex).zfill(3)) writer.writerow(LRC) # 将每首哥编号并将歌词写入从中文件中 rowindex+=1finally: csvfile.close() # 关闭csv文件
运行结果:
参考资料:Ryan Mitchell著,陶俊杰,陈小莉译《Python网络数据采集》
1 0
- Python爬虫实践:从中文歌词库抓取歌词
- python爬虫实践之网页抓取
- Python爬虫处理抓取数据中文乱码问题
- Python爬虫抓取图片,网址从文件中读取
- 从scrapy抓取同城网公交路线谈python爬虫
- Python爬虫之从网站图片中抓取文字
- python爬虫抓取图片
- Python爬虫抓取
- python 爬虫抓取奥数题
- python爬虫抓取-helloworld
- python 爬虫 基本抓取
- 爬虫实践---抓取小说网站
- python网络爬虫抓取图片
- Python爬虫抓取网页图片
- python爬虫CSDN文章抓取
- Python爬虫抓取csdn博客
- python 爬虫抓取心得分享
- 使用python爬虫抓取学术论文
- hdu 5174 Ferries Wheel(模拟)
- 杭电—1280 前m大的数
- sd卡下存储
- SGA_MAX_SIZE超过MEMORY_TARGET 导致无法启动
- pat 1043. Is It a Binary Search Tree (25)
- Python爬虫实践:从中文歌词库抓取歌词
- Linux Shell编程入门
- openstack的用户(user), 租户(tenant), 角色(role)概念区分
- Unity快速实现回合制游戏
- POJ2104 ---(区间第K 大)
- hello word
- C#语法灵活运用之排列组合算法
- JavaScript Object.prototype.constructor属性详解
- JAVA 反射API