本次使用python包中的requests庫、re庫和beautifulsoup庫對校園視頻網站http://10.22.1.18/Show/Index?PRIMARVIDEO_ID=11792 電視劇青春期撞上更年期進行視頻下載。
步驟如下:
首先需要根據url獲得網頁源代碼
- 根據源代碼中的是視頻地址特性可以發現視頻鏈接存儲在script標簽的腳本中。找到對應的視頻id,第一集為11792。通過視頻id設置對應的集數。
- 使用beautiful庫對script標簽進行查找。獲得script標簽中對應的文本。
- 使用正則表達式r'((http|ftp|https)://).+.mp4' 對視頻鏈接進行查找獲取,調用re.search() API。
- 使用requests庫中的get函數獲取視頻文件內容并使用
獲得本地文件
image.png
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 02 14:46:36 2017
@author: Sean Chang
"""
import requests
import re
from bs4 import BeautifulSoup
def getHTMLText(url):
#返回url對應的網頁源代碼
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def vedioaddress(url,num):
n1 = 11791 #第一集的編號-1
url = url + str(n1+num)
return url
def getVedioAddress(url,num):
html = getHTMLText(vedioaddress(url,num))
soup = BeautifulSoup(html, 'html.parser')
a = soup.find_all('script')
address= ''
mstr= ''
for i in a:
if (i.string != None):
mstr = mstr+str(i.string)
address = re.search(r'((http|ftp|https)://).+\.mp4',mstr).group(0).split("'")[0]
return address
def main():
vediourl = getVedioAddress('http://10.22.1.18/Show/Index?PRIMARVIDEO_ID=',1)
r = requests.get(vediourl)
with open(vediourl.split('/')[-1], "wb") as code:
code.write(r.content)
main()