从小到大,一直很喜欢听周杰伦唱的歌,可是相信很多人和我一样,并不能完全听明白歌词究竟是什么,今天我们就来研究一下周董最喜欢在歌词中用的词,这一小节的构思是这样的,我们爬取周杰伦的歌词信息,并且将其进行分词,来看一下什么样的词出现的频率最高,我们将这一整个过程分为两部分,前一部分是抓取,后一部分是分析,分析部分将在数据可视化里面进行处理。
分析
既然是抓取歌词信息,那么最好的地方就是那些音乐平台了,由于平时使用网易云音乐比较多一些,就打算从网页版的云音乐入手,可是对网页进行分析以后发现,云音乐使用了比较多的ajax异步加载,区区的几百首歌,我也是懒得去进一步的分析了,对比发现,虾米音乐还比较方便,因此最终选择了虾米音乐,这也是为什么你看到项目的名称是云音乐了。
我们直接新建一个项目,就叫yunyinyue吧。
项目代码
item.py
import scrapy
class YunyinyueItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
song = scrapy.Field()
由于全是周杰伦的歌,我们的item内容简单的就两个,一个是歌名,一个是歌词。
spider.py
from scrapy import Spider,Request
from yunyinyue.items import YunyinyueItem
from urllib.parse import quote
from lxml import etree
class YunyinyueSpider(Spider):
name = 'yunyinyue'
def start_requests(self):
singer = '周杰伦'
raw_url = 'http://www.xiami.com/search/song/page/{}?spm=a1z1s.3521869.0.0.Nv2jr2&key={}&category=-1'
for i in range(44):
url = raw_url.format(str(i+1), quote(singer))
yield Request(url=url, callback=self.parse)
def parse(self, response):
selector = etree.HTML(response.text)
hrefs = selector.xpath('//td[@class="song_name"]/a[1]/@href')
titles = selector.xpath('//td[@class="song_name"]/a[1]/@title')
for href,title in zip(hrefs, titles):
yield Request(url=href, callback=self.parse_content, meta={'title': title})
def parse_content(self,response):
selector = etree.HTML(response.text)
song_list = selector.xpath('//div[@class="lrc_main"]/text()')
song = []
for line in song_list:
song.append(line.strip())
result = ','.join(song)
item = YunyinyueItem()
item['title'] = response.meta['title']
item['song'] = result
yield item
具体的逻辑是这样的,我们首先打开虾米网页,搜索周杰伦,发现收录的歌曲数目是44页,因此我们对这44页进行分别请求,每一页的歌曲数目是20个,包含了歌名和相应的链接,我们拿到歌名和链接列表,分别在对每一个链接进行请求,你会发现链接页面的中间内容就是歌词信息了,直接提取即可。
注意我们需要对拿到的歌词进行简单地处理,因为歌词里面包含了不少的\n\t\r这类的字符,我们直接通过strip()方法,将其去除。
pipelines.py
import pymongo
class MongoPipeline(object):
collection = 'zhoujielun'
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri = crawler.settings.get('MONGO_RUI'),
mongo_db = crawler.settings.get('MONGO_DB')
)
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
def close_spider(self, spider):
self.client.close()
def process_item(self, item, spider):
table = self.db[self.collection]
data = dict(item)
table.insert_one(data)
return item
数据的存储就真的没什么好说的了。
middlewares.py
import scrapy
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
import random
class MyUseragentMiddleware(UserAgentMiddleware):
'''
设置User-Agent
'''
def __init__(self, user_agent):
self.user_agent = user_agent
@classmethod
def from_crawler(cls, crawler):
return cls(
user_agent=crawler.settings.get('USER_AGENTS')
)
def process_request(self, request, spider):
agent = random.choice(self.user_agent)
request.headers['User-Agent'] = agent
class MyCookieMiddleware(object):
def __init__(self, cookies):
self.cookie = random.choice(cookies)
@classmethod
def from_crawler(cls, crawler):
return cls(
cookies=crawler.settings.get('COOKIES')
)
def process_request(self, request, spider):
request.cookies = self.cookie
我们这里加一个cookie中间件,将我们自己的cookie信息加上。因为网站后面的页面只有登录才能看。
settings.py
BOT_NAME = 'yunyinyue'
SPIDER_MODULES = ['yunyinyue.spiders']
NEWSPIDER_MODULE = 'yunyinyue.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2.5
COOKIES_ENABLED = True
TELNETCONSOLE_ENABLED = False
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
DOWNLOADER_MIDDLEWARES = {
'yunyinyue.middlewares.MyUseragentMiddleware': 400,
'yunyinyue.middlewares.MyCookieMiddleware': 450,
}
COOKIES = [
{'key1': 'value1','key2': 'value2', ...}, # 你的cookie,注意是字典的形式
]
USER_AGENTS = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)",
"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)",
"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0",
"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
"Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
]
ITEM_PIPELINES = {
'yunyinyue.pipelines.MongoPipeline': 300,
}
MONGO_URI = 'mongodb://localhost:27017'
MONGO_DB = "music"
注意这里需要添加上你的cookie,直接去浏览器上复制,在转化成字典格式即可。
至此,我们的项目就结束了,直接运行,就可以将歌词信息存入数据库了。
你可以去github下载以上的代码和相应的歌词数据。