知識點
- 爬蟲基本流程
- re正則表達式簡單使用
- requests
- json數據解析方法
- 視頻數據保存
- Python 3.8
- Pycharm
-
確定需求 (爬取的內容是什么東西?)
都通過開發者工具進行抓包分析
分析視頻播放url地址 是可以從哪里獲取到
如果我們想要的數據內容 是 音頻數據/視頻數據 (media)
雖然說知道視頻播放地址, 但是我們還需要知道這個播放地址 可以從什么地方獲取 -
發送請求, 用python代碼模擬瀏覽器對於目標地址發送請求
-
獲取數據, 獲取服務器給我們返回的數據內容
-
解析數據, 提取我們想要數據內容, 視頻標題/視頻url地址
-
保存數據
今天要爬取的目標就是這個
先打開一個視頻,查看id
打開開發者工具,查找
拿到目標url
import requests # 數據請求模塊 pip install requests (第三方模塊) import pprint # 格式化輸出模塊 內置模塊 不需要安裝 import re # 正則表達式 import json
def get_response(html_url): # 用python代碼模擬瀏覽器 # headers 把python代碼進行偽裝 # user-agent 瀏覽器的基本標識 headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36' } # 用代碼直接獲取的 一般大多數都是直接 cookie response = requests.get(url=html_url, headers=headers) return response
def get_video_info(video_id): html_url = f'https://liveapi.huya.com/moment/getMomentContent?videoId={video_id}&uid=&_=1634127164373' response = get_response(html_url) title = response.json()['data']['moment']['title'] # 視頻標題 video_url = response.json()['data']['moment']['videoInfo']['definitions'][0]['url'] video_info = [title, video_url] return video_info
def get_video_id(html_url): html_data = get_response(html_url).text result = re.findall('<script> window.HNF_GLOBAL_INIT = (.*?) </script>', html_data)[0] # 需要把獲取的字符串數據, 轉成json字典數據 json_data = json.loads(result)['videoData']['videoDataList']['value'] # json_data 列表 里面元素是字典 # print(json_data) video_ids = [i['vid'] for i in json_data] # 列表推導式 # lis = [] # for i in json_data: # lis.append(i['vid']) # print(video_ids) # print(type(json_data)) return video_ids # 目光所至 我皆可爬 def main(html): video_ids = get_video_id(html_url=html) for video_id in video_ids: video_info = get_video_info(video_id) save(video_info[0], video_info[1])
def save(title, video_url): # 保存數據, 也是還需要對於播放地址發送請求的 # response.content 獲取響應的二進制數據 video_content = get_response(html_url=video_url).content new_title = re.sub(r'[\/:*?"<>|]', '_', title) # 'video\\' + title + '.mp4' 文件夾路徑以及文件名字 mode 保存方式 wb二進制保存方式 with open('video\\' + new_title + '.mp4', mode='wb') as f: f.write(video_content) print('保存成功: ', title)
if __name__ == '__main__': # get_video_info('589462235') video_info = get_video_info('589462235') save(video_info[0], video_info[1]) for page in range(1, 6): print(f'正在爬取第{page}頁的數據內容') # python基礎入門課程 第一節課 講解的知識點 字符串格式化方法 url = f'https://v.huya.com/g/all?set_id=31&order=hot&page={page}' main(url)