python在爬虫方面的应用
.整体设计目标
通过本程序爬取网易云歌曲的歌词并输出展现给用户,为了让其显得更加人性化,设计了由用户输入想爬取歌词歌曲的id,而且有是否将歌词保存到文本文件、是否用歌词生成词云选项。
代码总体框架
- 效果预览
本爬虫程序用到以下几个第三方库,需要自己去下载安装:
requests、json、re、os、jieba、wordcloud、PIL.Image、numpy库。
首先要去网易云爬取歌词(此片代码是借鉴一位前辈的,我又稍加修改让歌词展现的更加简洁一点):
import requests
import json
import re
music_id = input("请输入歌曲的id:")
#我们这里以周杰伦的“布拉格广场”为例,id=210049
headers={"User-Agent" : "Mozilla/5.0(Windows NT 10.0; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 ",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "zh-CN,zh;q=0.9",
"Connection" : "keep-alive",
"Accept-Charset" : "GB2312,utf-8;q=0.7,*;q=0.7"}
url = 'http://music.163.com/api/song/lyric?'+ 'id=' + music_id + '&lv=1&kv=1&tv=-1'
r = requests.get(url,headers=headers,allow_redirects=False)
#allow_redirects设置为重定向的参数
#headers=headers添加请求头的参数,冒充请求头
#用js将获取的歌词源码进行解析
json_obj = r.text#.text返回的是unicode 型的数据,需要解析
j = json.loads(json_obj)#进行json解析
words = j['lrc']['lyric'] #将解析后的歌词存在words变量中
#解析后的歌词发现每行歌词前面有时间节点,将它进行美化一下:
pattern = '\\(.*?\\)|\\{.*?}|\\[.*?]'
text1 = re.sub(pattern, "", words)#用正则表达式将时间剔除
print(text1)#text1是歌词
再写个选择项是否写入文件:
创建菜单选项
def select(writefile):
print ( '''
是否将歌词保存到您的歌词文件内?
1:写入到文件
2:不写入
''' )
while True:
choice = input( "您的选择是:" )
if choice == '1':
write_into_file()
break
if choice == '2':
print( "主人不写入的话,以后忘词了不要怪妲己哦!" )
break
else:
print( "Error! you must input a valid letter!Please try again!\n" )
continue
select( 'writefile' ) # 调用是否写入文件函数
然后定义歌词存入文件函数(我写的有点繁琐,但初心是为了让用户明白程序做了什么<小洁癖>):
#创建一个文件用来保存歌词
#可以选择是否保存到文件
import os
def write_into_file():
path = os.getcwd() + '/'
files = os.listdir( path )
#查找文件
for f in files:
if f == 'music_words.txt':
print( "有该歌词文件" )
with open(f, 'w') as file: # 'w'代表者每次运行都覆盖内容
file.write( text1 )
print( "歌词写入完成" )
file.close()
break
else:
print( "没有该歌词文件" )
def create_text(filename):
path = os.getcwd() + '/' # 当前目录为文件路径
file_path = path + filename + '.txt'
print( "已经帮你自动创建歌词文件" )
file = open(file_path, 'w')
file.write( text1 )
print("歌词写入完成")
file.close()
create_text('music_words') # 调用函数
那现在就剩最后的生成词云的那部分了,生成词云之前我们也做一个选择项,将选择权交给用户<小洁癖>。此处的选择项代码和前面的文件写入选择项大同小异,我就不再讲了。直接上后面的:
def creatcloud():
def trans_CN(text):
# 接收分词的字符串
word_list = jieba.cut( text )
# 分词后在单独个体之间加上空格
result = " ".join( word_list )
return result
text = trans_CN( text1 )
#print( text )
mask = np.array( image.open( os.getcwd()+'/1.jpg' ) )
wordcloud = WordCloud(
# 添加遮罩层
mask=mask, # 逗号一定要写
# 生成中文字的字体,必须要加,不然看不到中文,会出现空框乱码
font_path="C:/Windows/Fonts/simfang.ttf"
).generate( text )
image_produce = wordcloud.to_image()
image_produce.show()
creatcloud()
现在我们所需要的代码块就已经编写完毕我们将代码全部合在一起,附上完成代码:、
代码运行时会提示找不到1.jpg文件错误。
解决方法:在当前文件夹下放一张照片(白底),然后重命名为1.jpg即可。
import requests
import json
import re
import os
import jieba
from wordcloud import WordCloud
import PIL.Image as image
import numpy as np
music_id = input("请输入歌曲的id:")
#我们这里以周杰伦的“布拉格广场”为例,id=210049
headers={"User-Agent" : "Mozilla/5.0(Windows NT 10.0; WOW64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 ",
"Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language" : "zh-CN,zh;q=0.9",
"Connection" : "keep-alive",
"Accept-Charset" : "GB2312,utf-8;q=0.7,*;q=0.7"}
url = 'http://music.163.com/api/song/lyric?'+ 'id=' + music_id + '&lv=1&kv=1&tv=-1'
#用这行代码可以绕过网易云的token请求
r = requests.get(url,headers=headers,allow_redirects=False)
#allow_redirects设置为重定向的参数
#headers=headers添加请求头的参数,冒充请求头
#用js将获取的歌词源码进行解析
json_obj = r.text#.text返回的是unicode 型的数据,需要解析
j = json.loads(json_obj)#进行json解析
words = j['lrc']['lyric'] #将解析后的歌词存在words变量中
#解析后的歌词发现每行歌词前面有时间节点,将它进行美化一下:
pattern = '\\(.*?\\)|\\{.*?}|\\[.*?]'
text1 = re.sub(pattern, "", words)#用正则表达式将时间剔除
print(text1)#text1是歌词
#创建一个文件用来保存歌词
#可以选择是否保存到文件
def write_into_file():
path = os.getcwd() + '/'
files = os.listdir( path )
#查找文件
for f in files:
if f == 'music_words.txt':
print( "有该歌词文件" )
with open(f, 'w') as file: # 'w'代表者每次运行都覆盖内容
file.write( text1 )
print( "歌词写入完成" )
file.close()
break
else:
print( "没有该歌词文件" )
def create_text(filename):
path = os.getcwd() + '/' # 当前目录为文件路径
file_path = path + filename + '.txt'
print( "已经帮你自动创建歌词文件" )
file = open(file_path, 'w')
try:
file.write( text1 )
print("歌词写入完成")
except:
return("歌词写入异常")
file.close()
create_text('music_words') # 调用函数
# 创建菜单选项
def select(writefile):
print ( '''
是否将歌词保存到您的歌词文件内?
1:写入到文件
2:不写入
''' )
while True:
choice = input( "您的选择是:" )
if choice == '1':
write_into_file()
break
if choice == '2':
print( "主人不写入的话,以后忘词了不要怪妲己哦!" )
break
else:
print( "Error! you must input a valid letter!Please try again!\n" )
continue
select( 'writefile' ) # 调用是否写入文件函数
def creatcloud():
def trans_CN(text):
# 接收分词的字符串
word_list = jieba.cut( text )
# 分词后在单独个体之间加上空格
result = " ".join( word_list )
return result
text = trans_CN( text1 )
#print( text )
mask = np.array( image.open( os.getcwd()+'/1.jpg' ) )
wordcloud = WordCloud(
# 添加遮罩层
mask=mask, # 逗号一定要写
# 生成中文字的字体,必须要加,不然看不到中文,会出现空框乱码
font_path="C:/Windows/Fonts/simfang.ttf"
).generate( text )
image_produce = wordcloud.to_image()
image_produce.show()
#再定义一个选择函数
def select2():
print( '''
是否根据该歌词生成词云?
1.yes
2.no
''' )
while True:
select = input( " your choice is:" )
if select == '1':
creatcloud()
break
if select == '2':
print( "主人不看词云,妲己觉得好可惜" )
break
else:
print( "Error , you must input a vailid letter! please try again.\n" )
continue
select2()
由于本人还是初学Python的小白,本程序肯定还有很多不足,还请各位大神多加担待、指点。若有任何疑问或者建议可直接评论在下方或私我。