Python selenium抓取虎牙短視訊程式碼例項
阿新 • • 發佈:2020-03-03
今天閒著沒事,用selenium抓取視訊儲存到本地,只爬取了第一頁,只要小於等於5分鐘的視訊。。。
為什麼不用requests,沒有為什麼,就因為有些網站正則和xpath都提取不出來想要的東西,要麼就是接口出來的資料加密,要麼就因為真正的視訊url規律難找!
selenium幾行程式碼輕輕鬆鬆就搞定!
安裝selenium庫,設定無介面模式
程式碼如下:
from selenium import webdriver from selenium.webdriver.chrome.options import Options import requests #設定無介面模式 chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') class VideoCrawl(object): video_box=[]#收集video真正的url def __init__(self,url): self.driver=webdriver.Chrome(executable_path=r"C:\Program Files\python\Lib\site-packages\selenium\webdriver\chrome\chromedriver.exe",options=chrome_options)#設定無介面模式 self.driver.get(url) #程式執行完畢,解構函式關閉selenium def __del__(self): print("爬取結束。。。。。",len(VideoCrawl.video_box),VideoCrawl.video_box) self.driver.close() def run(self): self.get_detail_info() #獲取列表頁所有詳情頁的url def get_detail_info(self): detail_info = self.driver.find_elements_by_xpath('//a[@class="video-wrap statpid"]') detail_url=[] for i in detail_info: detail_url.append(i.get_attribute('href'))#獲取視訊頁url video_playtime_list=self.driver.find_elements_by_xpath('//span[@class="video-duration"]') video_playtime_list=[i.text for i in video_playtime_list] for res in zip(detail_url,video_playtime_list): playtime=res[1].split(":")[0] # print("playtime--------",playtime) if int(res[1].split(":")[0])<=5:#播放時間小於5分鐘的要 # print(res[0],"解析的url",playtime) self.parse_video(res[0],res[1]) else: pass #解析詳情頁 def parse_video(self,url,t): self.driver.get(url) videoobj = self.driver.find_elements_by_xpath('//video') video_url=videoobj[0].get_attribute('src') title=self.driver.find_elements_by_xpath('//h1[@class="video-title"]')[0].text print('video_url--------',video_url,title,t) #儲存video到本地 self.save_video(video_url,t) #類變數統計video_url VideoCrawl.video_box.append(video_url) #儲存,請求video_url,二進位制儲存為mp4 def save_video(self,t): filename="video"+title+"-"+t.replace(":","")+".mp4" video=requests.get(url).content with open(filename,"wb") as file: file.write(video) print(f"{filename}寫入檔案完畢") if __name__ == '__main__': crawl=VideoCrawl('https://v.huya.com/cat/7') crawl.run()
執行結果如下:
"C:\Program Files\python\python.exe" C:/Users/Administrator.SC-201903160419/Desktop/note/exer/myapp.py video_url-------- https://huya-w10.huya.com/2005/265917310/1300/d973823b0f437c9d78fc40b9691fdb54.mp4 【軒子小劇場】最意外的自行車 04:23 video【軒子小劇場】最意外的自行車-0423.mp4寫入檔案完畢 video_url-------- https://huya-w10.huya.com/2006/267302224/1300/f8a363ec243e4adb2857491f695bc118.mp4 軒子巨2兔:軒子教你演戲 05:06 video軒子巨2兔:軒子教你演戲-0506.mp4寫入檔案完畢 video_url-------- https://huya-w6.huya.com/2005/264805062/1300/582b726b05db31fc12a1e5557011a6bf.mp4 【麥秀彩兒】跳個舞吧 05:58 video【麥秀彩兒】跳個舞吧-0558.mp4寫入檔案完畢 video_url-------- https://huya-w10.huya.com/2005/264956230/1300/97fa603f7b174ec30c19013f894bd108.mp4 軒子小劇場:你的女僕請簽收 01:18 Process finished with exit code -1
都可以正常播放。。。
切記:自己娛樂下練練手刪了即可,千萬不要用於商業用途哦!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。