B站在小視頻功能處提供了 API 接口,今天的任務(wù)爬取Bilibili視頻~
B 站視頻網(wǎng)址:https://vc.bilibili.com/p/eden/rank#/?tab=全部
此次爬取視頻蛉鹿,我們爬取前100個(gè)~
我們做好前期準(zhǔn)備~
1:Chrome 瀏覽器 (能使用開發(fā)者模式的瀏覽器都行)
2:Vim (編輯器任選,老實(shí)人比較喜歡Vim界面往湿,所以才用這個(gè)啦)
3:Python3 開發(fā)環(huán)境
4:Kali Linux (其實(shí)隨便一個(gè)操作系統(tǒng)都行啦)
5:API 尋找 && 提取
我們通過 F12 打開開發(fā)者模式妖异,然后在 Networking -> Name 字段下找到這個(gè)鏈接:
我們查看一下 Headers 屬性
我們可以看到Request URL這個(gè)屬性值,我們向下滑動(dòng)加載視頻的過程中领追,發(fā)現(xiàn)只有這段url是不變的他膳。
next_offset 會(huì)一直變化,我們可以猜測绒窑,這個(gè)可能就是獲取下一個(gè)視頻序號(hào)棕孙,我們只需要把這部分參數(shù)取出來,把 next_offset 寫成變量值些膨,用 JSON 的格式返回到目標(biāo)網(wǎng)頁即可散罕。
代碼實(shí)現(xiàn)
我們通過上面的嘗試寫了段代碼,發(fā)現(xiàn) B 站在一定程度上做了反爬蟲操作傀蓉,所以我們需要先獲取 headers 信息欧漱,否則下載下來的視頻是空的,然后定義 params 參數(shù)存儲(chǔ) JSON 數(shù)據(jù)葬燎,然后通過 requests.get 去獲取其參數(shù)值信息误甚,用 JSON 的格式返回到目標(biāo)網(wǎng)頁即可缚甩,實(shí)現(xiàn)代碼如下:
def get_json(url):
headers = {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
params = {
'page_size': 10,
'next_offset': str(num),
'tag': '今日熱門',
'platform': 'pc'
}
try:
html = requests.get(url,params=params,headers=headers)
return html.json()
except BaseException:
print('request error')
pass
為了能夠清楚的看到我們下載的情況,我們折騰了一個(gè)下載器上去窑邦,實(shí)現(xiàn)代碼如下:
def download(url,path):
start = time.time() # 開始時(shí)間
size = 0
headers = {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
response = requests.get(url,headers=headers,stream=True) # stream屬性必須帶上
chunk_size = 1024 # 每次下載的數(shù)據(jù)大小
content_size = int(response.headers['content-length']) # 總大小
if response.status_code == 200:
print('[文件大小]:%0.2f MB' %(content_size / chunk_size / 1024)) # 換算單位
with open(path,'wb') as file:
for data in response.iter_content(chunk_size=chunk_size):
file.write(data)
size += len(data) # 已下載的文件大小
效果如下:
將上面的代碼進(jìn)行匯總擅威,整個(gè)實(shí)現(xiàn)過程如下:
#!/usr/bin/env python#-*-coding:utf-8-*-import requestsimport randomimport timedef get_json(url):
headers = {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
params = {
'page_size': 10,
'next_offset': str(num),
'tag': '今日熱門',
'platform': 'pc'
}
try:
html = requests.get(url,params=params,headers=headers)
return html.json()
except BaseException:
print('request error')
passdef download(url,path):
start = time.time() # 開始時(shí)間
size = 0
headers = {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
response = requests.get(url,headers=headers,stream=True) # stream屬性必須帶上
chunk_size = 1024 # 每次下載的數(shù)據(jù)大小
content_size = int(response.headers['content-length']) # 總大小
if response.status_code == 200:
print('[文件大小]:%0.2f MB' %(content_size / chunk_size / 1024)) # 換算單位
with open(path,'wb') as file:
for data in response.iter_content(chunk_size=chunk_size):
file.write(data)
size += len(data) # 已下載的文件大小
if __name__ == '__main__':
for i in range(10):
url = 'http://api.vc.bilibili.com/board/v1/ranking/top?'
num = i*10 + 1
html = get_json(url)
infos = html['data']['items']
for info in infos:
title = info['item']['description'] # 小視頻的標(biāo)題
video_url = info['item']['video_playurl'] # 小視頻的下載鏈接
print(title)
# 為了防止有些視頻沒有提供下載鏈接的情況
try:
download(video_url,path='%s.mp4' %title)
print('成功下載一個(gè)!')
except BaseException:
print('涼涼,下載失敗')
pass
time.sleep(int(format(random.randint(2,8)))) # 設(shè)置隨機(jī)等待時(shí)間
爬取效果圖如下:
結(jié)果:
似乎爬取的效果還可以,當(dāng)然喜歡的朋友不要忘記點(diǎn)贊分享轉(zhuǎn)發(fā)哦冈钦。