原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明出處,歡迎關(guān)注微信公眾號(hào):Romi的雜貨鋪
回復(fù)b站每日排行榜爬蟲獲取全部源碼
爬取B站排行榜前100名的視頻名稱,作者和播放量,用到的主要有request庫(kù)獲取網(wǎng)頁(yè)信息,用正則解析網(wǎng)頁(yè)并使用openpyxl將信息保存在Excel中
第一部分為請(qǐng)求網(wǎng)頁(yè)獲取信息部分,request庫(kù)的基本用法
def get_html_text(url,self_header):
try:
response = requests.get(url,headers=self_header,timeout=30)
response.raise_for_status()
response.encoding = response.apparent_encoding
#print(response.text)
return response.text
except:
return ""
第二部分為用正則表達(dá)式解析網(wǎng)頁(yè)內(nèi)容并保存到Excel
def re_get_inf(html):
list=[]
rank_list=re.findall(r'<div class="num">(\d*)</div>',html)#排名
title_list=re.findall(r'<div class="info"><a href=[\s\S]*?class="title">([\s\S]*?)</a><!---->',html)#視頻名稱
play_num=re.findall(r'<div class="detail"><span class="data-box"><i class="b-icon play"></i>(\d*.\d*)\S</span>',html)#播放量
author_list=re.findall(r'<span class="data-box"><i class="b-icon author"></i>([\s\S]*?)</span>',html)#UP主名稱
wb=Workbook()#新建保存文件
sheet=wb.active
sheet.append(['rank','title','playnum','author'])#寫入標(biāo)題名稱
for i in range(len(rank_list)):
rank = rank_list[i]
title = title_list[i]
playnum=play_num[i]
author=author_list[i]
sheet.append([rank,title,playnum,author])#寫入數(shù)據(jù)
wb.save('bilibili_rankdata.xlsx')#保存文件
完整代碼如下所示,代碼與結(jié)果文件鏈接:
https://github.com/smilecoc/bilibili_rankdata