import requests
from bs4 import BeautifulSoup
import time
headers = {"User-Agent":"Mozilla/5.0"}
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('-')[1],
'time':time.get_text().strip()
}
print(data)
if __name__=='__main__':
urls = ['https://www.kugou.com/yy/rank/home/{}-8888.html?from=rank'.format(str(i)) for i in range(1,24)]
for url in urls:
get_info(url)
time.sleep(1)
当你看到这个程序,OK,就不要继续阅读了,如果有点懵,请继续阅读。
- 导库
导入程序需要的库,这个不需要过多解释。requests库用于请求网页获取网页数据。BeautifulSoup用于解析网页数据,time库的sleep()方法可以让程序暂停。 - 模拟浏览器
伪装成浏览器,让爬虫更加稳定。 - 函数
3.1 select函数
- soup.select(‘div’):所有名为< div >的元素。
- soup.select(’#author’):带有id属性名为author的元素。
- soup.select(’.notice’):所有使用CSS class 属性名为notice的元素
- soup.select(‘div span’):所有在< div >元素之内的元素
- soup.select(‘div > span’):所有直接在< div >元素之内的< span >元素,中间没有其他元素
- soup.select(‘input[name]’):所有名为< input >,并且有一个name属性,其值无所谓的元素
- soup.select(‘input[type=“button”]’):所有名为< input >,并有一个type属性,其值为button。
3.2 strip()函数
strip()字符串方法将返回一个新的字符串,它的开头或末尾都没有空白字符。
lstrip()和rstrip()方法将相应删除左边或右边的空白字符。
3.3split()函数
split()以空格为分隔符将字符串拆成多个部分,并将这些部分都存储到一个列表中。
- 主函数
程序主入口。