爬取的内容为酷狗榜单中酷狗top500的音乐信息,如图所示。
网页版酷狗不能手动翻页,进行下一步的浏览。但通过观察第一页的URL:
http://www.kugou.com/yy/rank/home/1-8888.html
这里尝试把数字1换为数字2,进行浏览,恰好返回的是第2页的信息(下图)。进行多次尝试,发现更换不同数字即为不同页面,故只需更改home/后面的数字即可。由于每页显示的为22首歌曲,所以总共需要23个URL
import requests
from bs4 import BeautifulSoup
import time
headers = {
‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36‘
}
def get_info(url):
wb_data = requests.get(url,headers=headers)
soup = BeautifulSoup(wb_data.text,‘lxml‘)
ranks = soup.select(‘span.pc_temp_num‘)
titles = soup.select(‘div.pc_temp_songlist > ul > li > a‘)
times = soup.select(‘span.pc_temp_tips_r > span‘)
for rank,title,time in zip(ranks,titles,times):
data = {
‘rank‘:rank.get_text().strip(),
‘singer‘:title.get_text().split(‘-‘)[0],
‘song‘:title.get_text().split(‘-‘)[0],
‘time‘:time.get_text().strip()
}
print(data)
if __name__ == ‘__main__‘:
urls = [‘http://www.kugou.com/yy/rank/home/{}-8888.html‘.format(str(i)) for i in range(1,24)]
for url in urls:
get_info(url)
time.sleep(1)
原文地址:https://www.cnblogs.com/wuxingqueshui/p/10049824.html