前言
事实上如果只是对一个人的歌单进行爬取完全可以直接元素审查复制后用正则表达式筛选出自己所需。
关于selenium
这个库可以模拟浏览器的行为,与requests和urllib不一样的是它可以爬取网页的内联框架。
我的具体想法
我想爬取我的网易云音乐歌单并且将获得的数据进行一波分析。
对网页进行元素审查后发现其歌单是内联在body内的另一个html,无法直接进行爬取,只能使用selenium。
爬取网页内容写入txt
sprider.py
from selenium import webdriver
from bs4 import BeautifulSoup
browser = webdriver.Firefox()
browser.get("your url")
iframe = browser.find_element_by_id("g_iframe")
browser.switch_to.frame(iframe)
with open("html.txt",'w',encoding='utf-8') as f:
f.write(browser.page_source)
print("任务完成!")
browser.close()
这里因为网易云歌单中有内联框架,需要使用browser.switch_to.frame(iframe)来切换
所需数据的获取
getdata.py
from bs4 import BeautifulSoup
with open("html.txt",'r',encoding="utf-8") as f:
soup = BeautifulSoup(f,'html5lib')
div = soup.find_all(attrs={"class":"text"})
for i in div:
name = i.get("title")
if name:
with open("singer_name.txt",'a',encoding="utf-8") as f:
f.write(name+"\n")
这里只是Beautifulsoup的应用
将获得的数据写入txt中
singer_name.txt大概内容如下
........
林宥嘉
林宥嘉
林宥嘉
王菲
张柏芝/傅佩嘉
王菲
王菲
王菲
张学友
林宥嘉
林宥嘉
........
可以看出来我很喜欢林宥嘉的歌了。。。
生成简单词云
from wordcloud import WordCloud
import matplotlib.pyplot as plt
font = "C:/Windows/Fonts/simhei.ttf"
with open("singer_name.txt","r",encoding="utf-8") as f:
text =f.read()
wordcloud = WordCloud(collocations=False, font_path=font, width=1400, height=1400, margin=2).generate(text.lower())
plt.imshow(wordcloud,interpolation='bilinear')
plt.axis("off")
plt.show()
wordcloud.to_file("ciyun.png")
效果如下
词云
后续
事实上,这只是wordcloud的简单应用,因为我太懒了就没去学这个的复杂用法,主要的还是学会selenium的使用。
欢迎访问我的博客www.redmango.top