前言
作爲一個僞守望迷,如何快速上手某個新英雄呢?
自然是查看官方的視頻教程了!
本次博主將會給位守望迷們講解如何使用python從守望先鋒官網爬取英雄教學視頻。
環境準備
本次教程將會用到如下內容,爲完美享用本次教程大餐,各位讀者請儘可能的使用和博主相同的版本。
- python----版本:3.7.2(這個沒啥硬性要求,只要是python3的即可)
- requests庫----版本:2.22.0(這個沒啥硬性要求,只要不要使用遠古版本即可)
- lxml庫----版本:4.4.1(這個沒啥硬性要求,只要lxml庫中包含etree模塊即可)
- 谷歌瀏覽器----版本要求暫無
- 一雙手和睿智的頭腦----相信各位讀者大大都有。
網頁分析
1.首先我們打開守望官網中的英雄視頻教程頁面,鏈接:https://ow.blizzard.cn/media/
我們右鍵視頻選擇【檢查】
打開網頁源代碼
可以看到視頻的鏈接存在於【class】屬性爲【media-item m-lg】的【li】標籤中,內容存在於【data-mp4】屬性中
嘗試打開該鏈接,驗證是否可以成功打開視頻。
視頻鏈接:https://blz-videos.nosdn.127.net/1/OverWatch/AnimatedShots/Overwatch_AnimatedShot_CinematicTrailer.mp4
可以看到成功打開了視頻。
代碼
# -*- coding:utf-8 -*-
#時間:2019年12月19日
#作者:貓先生的早茶
import requests;
from lxml import etree;
class SHOUWANGXIANFENG():
def __init__(self):
"""定義預定參數"""
#守望官網中的英雄視頻教程頁面url
self.page_url = "https://ow.blizzard.cn/media/";
#設置請求頭
self.headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Cookie": "123456789",
"Host": "ow.blizzard.cn",
"Pragma": "no-cache",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
};
def download_video(self,video_info):
"""下載並保存視頻"""
video_header = {
"Accept": "*/*",
"Accept-Encoding": "identity;q=1, *;q=0",
"Accept-Language": "zh-CN,zh;q=0.9",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "blz-videos.nosdn.127.net",
"Pragma": "no-cache",
"Referer": "https://blz-videos.nosdn.127.net/1/OverWatch/AnimatedShots/Overwatch_AnimatedShot_CinematicTrailer.mp4",
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
}
#下載視頻內容
video_content = requests.get(url=video_info[1],headers=video_header,verify=False).content;
#保存視頻
#print (video_info[1]);
with open(video_info[0]+".mp4".replace(':','').replace(' ',''),mode='wb') as write_video:
write_video.write(video_content);
def main(self):
"""控制程序運行"""
#獲取頁面內容,(注意,可能會提示證書錯誤,這個不用管,不影響程序運行)
page_html = requests.get(url=self.page_url,headers=self.headers,verify=False).text;
#打印頁面內容
#print (page_html);
#將網頁轉換爲etree格式
page_html_etree = etree.HTML(page_html);
#匹配出視頻標題
video_title = page_html_etree.xpath("//li[@class='media-item ']/@data-title");
#匹配出視頻鏈接
video_url = page_html_etree.xpath("//li[@class='media-item ']/@data-mp4");
#將視頻標題和視頻鏈接壓縮在一起
video_infos = dict(zip(video_title,video_url));
#下載視頻
for video_info in video_infos.items():
self.download_video(video_info);
shouwangxianfeng = SHOUWANGXIANFENG();
shouwangxianfeng.main();