校园视频下载脚本

本次使用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()

你可能感兴趣的:(校园视频下载脚本)