如何使用python爬取B站排行榜Top100的視頻數據
記得收藏呀!!!
1、第三方庫導入
from bs4 import BeautifulSoup # 解析網頁 import re # 正則表達式,進行文字匹配 import urllib.request,urllib.error # 通過瀏覽器請求數據 import sqlite3 # 輕型數據庫 import time # 獲取當前時間
2、程序運行主函數
爬取過程主要包括聲明爬取網頁 -> 爬取網頁數據並解析 -> 保存數據
def main(): #聲明爬取網站 baseurl = "https://www.bilibili.com/v/popular/rank/all" #爬取網頁 datalist = getData(baseurl) # print(datalist) #保存數據 dbname = time.strftime("%Y-%m-%d", time.localtime()) dbpath = "BiliBiliTop100 " + dbname saveData(datalist,dbpath)
(1)在爬取的過程中采用的技術為:偽裝成瀏覽器對數據進行請求;
(2)解析爬取到的網頁源碼時:采用Beautifulsoup解析出需要的數據,使用re正則表達式對數據進行匹配;
(3)保存數據時,考慮到B站排行榜是每日進行刷新,故可以用當前日期進行保存數據庫命名。
3、程序運行結果
數據庫中包含的數據有:排名、視頻鏈接、標題、播放量、評論量、作者、綜合分數這7個數據。
4、程序源代碼
from bs4 import BeautifulSoup #解析網頁 import re # 正則表達式,進行文字匹配 import urllib.request,urllib.error import sqlite3 import time def main(): #聲明爬取網站 baseurl = "https://www.bilibili.com/v/popular/rank/all" #爬取網頁 datalist = getData(baseurl) # print(datalist) #保存數據 dbname = time.strftime("%Y-%m-%d", time.localtime()) dbpath = "BiliBiliTop100 " + dbname saveData(datalist,dbpath) #re正則表達式 findLink =re.compile(r'<a class="title" href="(.*?)" rel="external nofollow" ') #視頻鏈接 findOrder = re.compile(r'<div class="num">(.*?)</div>') #榜單次序 findTitle = re.compile(r'<a class="title" href=".*?" rel="external nofollow" rel="external nofollow" target="_blank">(.*?)</a>') #視頻標題 findPlay = re.compile(r'<span class="data-box"><i class="b-icon play"></i>([\s\S]*)(.*?)</span> <span class="data-box">') #視頻播放量 findView = re.compile(r'<span class="data-box"><i class="b-icon view"></i>([\s\S]*)(.*?)</span> <a href=".*?" rel="external nofollow" rel="external nofollow" target="_blank"><span class="data-box up-name">') # 視頻評價數 findName = re.compile(r'<i class="b-icon author"></i>(.*?)</span></a>',re.S) #視頻作者 findScore = re.compile(r'<div class="pts"><div>(.*?)</div>綜合得分',re.S) #視頻得分 def getData(baseurl): datalist = [] html = askURL(baseurl) #print(html) soup = BeautifulSoup(html,'html.parser') #解釋器 for item in soup.find_all('li',class_="rank-item"): # print(item) data = [] item = str(item) Order = re.findall(findOrder,item)[0] data.append(Order) # print(Order) Link = re.findall(findLink,item)[0] Link = 'https:' + Link data.append(Link) # print(Link) Title = re.findall(findTitle,item)[0] data.append(Title) # print(Title) Play = re.findall(findPlay,item)[0][0] Play = Play.replace(" ","") Play = Play.replace("\n","") Play = Play.replace(".","") Play = Play.replace("萬","0000") data.append(Play) # print(Play) View = re.findall(findView,item)[0][0] View = View.replace(" ","") View = View.replace("\n","") View = View.replace(".","") View = View.replace("萬","0000") data.append(View) # print(View) Name = re.findall(findName,item)[0] Name = Name.replace(" ","") Name = Name.replace("\n","") data.append(Name) # print(Name) Score = re.findall(findScore,item)[0] data.append(Score) # print(Score) datalist.append(data) return datalist def askURL(url): #設置請求頭 head = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0;Win64;x64) AppleWebKit/537.36(KHTML, likeGecko) Chrome/80.0.3987.163Safari/537.36" } request = urllib.request.Request(url, headers = head) html = "" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") #print(html) except urllib.error.URLError as e: if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reason) return html def saveData(datalist,dbpath): init_db(dbpath) conn = sqlite3.connect(dbpath) cur = conn.cursor() for data in datalist: sql = ''' insert into Top100( id,info_link,title,play,view,name,score) values("%s","%s","%s","%s","%s","%s","%s")'''%(data[0],data[1],data[2],data[3],data[4],data[5],data[6]) print(sql) cur.execute(sql) conn.commit() cur.close() conn.close() def init_db(dbpath): sql = ''' create table Top100 ( id integer primary key autoincrement, info_link text, title text, play numeric, view numeric, name text, score numeric ) ''' conn = sqlite3.connect(dbpath) cursor = conn.cursor() cursor.execute(sql) conn.commit() conn.close() if __name__ =="__main__": main()
到此這篇關於如何使用python爬取B站排行榜Top100的視頻數據的文章就介紹到這瞭,更多相關python B站視頻 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- 如何使用python爬取知乎熱榜Top50數據
- 用Python實現爬取百度熱搜信息
- Python7個爬蟲小案例詳解(附源碼)上篇
- Python正則表達式re.compile()和re.findall()詳解
- 使用pandas生成/讀取csv文件的方法實例