前言
事實上如果只是對一個人的歌單進行爬取完全可以直接元素審查復制后用正則表達式篩選出自己所需。
關于selenium
這個庫可以模擬瀏覽器的行為,與requests和urllib不一樣的是它可以爬取網(wǎng)頁的內(nèi)聯(lián)框架。
我的具體想法
我想爬取我的網(wǎng)易云音樂歌單并且將獲得的數(shù)據(jù)進行一波分析。
對網(wǎng)頁進行元素審查后發(fā)現(xiàn)其歌單是內(nèi)聯(lián)在body內(nèi)的另一個html,無法直接進行爬取,只能使用selenium。
爬取網(wǎng)頁內(nèi)容寫入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()
這里因為網(wǎng)易云歌單中有內(nèi)聯(lián)框架,需要使用browser.switch_to.frame(iframe)來切換
所需數(shù)據(jù)的獲取
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的應用
將獲得的數(shù)據(jù)寫入txt中
singer_name.txt大概內(nèi)容如下
........
林宥嘉
林宥嘉
林宥嘉
王菲
張柏芝/傅佩嘉
王菲
王菲
王菲
張學友
林宥嘉
林宥嘉
........
可以看出來我很喜歡林宥嘉的歌了。。。
生成簡單詞云
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")
效果如下

詞云
后續(xù)
事實上,這只是wordcloud的簡單應用,因為我太懶了就沒去學這個的復雜用法,主要的還是學會selenium的使用。
歡迎訪問我的博客www.redmango.top