文件名自定義(文件格式為.py),腳本內容:
#!/usr/bin/env python
#-*-coding:utf-8-*-
import requests
import random
import time
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
def download(url,path):
start = time.time() # 開始時間
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 # 每次下載的數據大小
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'] # 小視頻的標題
video_url = info['item']['video_playurl'] # 小視頻的下載鏈接
print(title)
# 為了防止有些視頻沒有提供下載鏈接的情況
try:
download(video_url,path='videos/%s.mp4' %title)
print('成功下載一個!')
except BaseException:
print('涼涼,下載失敗')
pass
time.sleep(int(format(random.randint(2,8)))) # 設置隨機等待時間
爬取效果如下:
爬取的文件:
生成一個windows平台可執行exe程序
工具安裝:pip install PyInstaller
生成exe程序:
pyinstaller -i test.ico -F Grasp.py
打包過程:
打包好的文件:
參數含義:
程序:
百度雲下載鏈接
鏈接:百度雲
提取碼:hqhr