江湖小白之一起学Python (十)开发视频网之抓取信息并展示

微风徐来,我情不自禁的摸了摸我油亮的头顶,嘴里哼着哥哥的风继续吹,思考下今天这章要写的内容,绞尽脑汁,为数不多的头发又掉了几根……从以前的英俊帅气慢慢朝着土肥圆在进化,哎,生活拖累了我啊!

上篇我们只是说了下web框架的搭建,那今天我们就开始使用flask的render_template的模块,实现加载模板页面将抓取的信息通过网页的形式来展示,下面我们直接上代码讲解,首先在上篇的video文件夹中创建一个__init__.py,你命名为其它的也可以,只是路径指向的时候要对应,在这个文件里,我们就把爬取啊,处理业务逻辑的方法就写到这个类里面,方便以后的代码维护及管理,代码如下:

video/__init.py

#coding:utf-8
import requests,re
from pyquery import PyQuery as pq

class Video():
    def __init__(self):
        #定义请求超时的时间
        self.timeout = 60

    #获取视频信息
    def get_video_info(self,weburl):
        #请求网址
        response = requests.get(url=weburl,timeout=self.timeout)
        response.encoding = response.apparent_encoding
        content = response.text
        #用pyquery格式化内容
        dochtml = pq(content)
        #获取视频页面中需要提取的信息
        title=dochtml("#vod>h2>.title").text()
        imgurl=dochtml(".lazy").attr("src")
        users=dochtml(".infos > dd").eq(1).text()
        detail=dochtml(".detail-desc-cnt > p").text()
        #定义一个object,存放以上的数据,以json的形式传递
        result = {}
        result["title"] = title
        result["imgurl"]=imgurl
        result["users"] = users
        result["detail"] = detail
        #这个网站中这里的标签有很多类型,这里我判断了2种,意思是swyun没有获取到内容就查找zdyun
        yunhtml=dochtml(".swyun").parent()(".play-list")
        if len(yunhtml)==0:
            yunlist=dochtml(".zdyun").parent()(".play-list>li").items()
        else:
            yunlist = yunhtml("li").items()
        #定义剧集集合
        episodes=[]
        #这里获取到的yunlist是一个对象集
        for p in yunlist:
            name = p.text()
            url = p('a').attr('href')
            pjson={}
            pjson["name"]=name
            pjson["url"] = "{}{}".format(re.search('http[s]?://[-\w.]+', weburl).group(),url)
            #将剧集的名称及对应的地址插入到集合中
            episodes.append(pjson)
        result["episodes"]=episodes
        #返回JSON结果集
        return result

if __name__ == '__main__':
    #调用方法调试一下
    videourl = 'https://www.juji.tv/dianshiju/linghunweixiugong/'
    v=Video()
    result=v.get_video_info(videourl)
    print(result)

这里就是一个请求网页并提取的过程,之前都讲过这里就不多说了,上面 有一点可以优化的就是if…else…,像上面在if中只有一个逻辑的我们可以简化下:

yunlist=dochtml(".zdyun").parent()(".play-list>li").items() if len(yunhtml)==0 else yunhtml("li").items()

有点类似JS中的三目运算表达式,不懂?没关系,请原谅我的自言自语……

这个video类创建好了,那我们就在main.py主文件中调用:

main.py

#coding:utf-8
from webvideo.app import app
from flask import render_template      #引入render_template模块加载模板页面
from webvideo.app.video import *       #引入刚刚实现的video类文件,*表示所有

# 主页面
@app.route("/")
def index():
    #要搜索的视频网址
    url = 'https://www.juji.tv/dianshiju/Helloxiaojie/'
    #初始video类
    v = Video()
    #调用其中的get_video_info方法获取返回的json集
    result = v.get_video_info(url)
    #通过render_template加载video.html模板页面,并向页面传递上面的json集
    return render_template("video.html",result=result)

那这个video.html在哪里,因为之前说过了,flask的默认模板文件是放在templates文件夹下的,代码如下:

templates/video.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        ul{
            list-style: none;
            margin: 0;
            padding: 0;
        }
        .content{
            width: 1000px;
            margin: 40px auto;
        }
        .video_search{
            width: 600px;
            border: 1px solid #ddd;
            height: 40px;
            display: flex;
        }
        .video_search_text{
            border: none;
            font-size: 14px;
            width: 480px;
            padding: 0 20px;
        }
        .video_search_btn{
            background-color: #eee;
            border: none;
            width: 80px;
            font-size: 16px;
        }
        .video_info{
            margin-top: 40px;
            display: flex;
        }
        .video_img{
            width: 225px;
            height: 300px;
            padding: 2px;
            border: 1px solid #ddd;
        }
        .video_title{
            font-size: 18px;
             font-weight: bold;
            line-height: 50px;
        }
        .video_txt{
            margin-left: 20px;
            margin-right: 20px;
        }
        .video_user{
            font-size: 16px;
        }
        .video_detail{
            margin-top: 20px;
            font-size: 14px;
            color: #999;
            line-height: 22px;
        }
        .video_online{
            margin-top: 40px;
            width: 100%;
            font-size: 16px;
            padding-left: 20px;
            line-height: 40px;
            border-bottom: 1px solid #ddd;
        }
        .video_ep{
            margin-top: 40px;
        }
        .video_ep ul li{
            float: left;
            margin-right: 20px;
            width: 158px;
            margin-bottom: 20px;
            padding: 10px 10px;
            border: 1px solid #ddd;
        }
        .video_ep ul li a{
            color: #ff5519;
            text-decoration: none;
        }
        .video_ep ul li a:hover{
            color: #ff9f49;
        }
        .video_ep_li{
            display: flex;
            justify-content: space-between;
        }
        .video_play a{
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .video_play_name{
            margin-left: 10px;
        }
        .video_play img,.video_down img{
            width: 20px;
            height: 20px;
        }
        .video_down{
            margin-left: 10px;
            border-left: 1px solid #ddd;
            padding-left: 10px;
        }
        .video_show{
            clear: both;
            width: 100%;
        }
        .video_con{
            margin-top: 120px;
        }
        .video_log{
            max-height: 300px;
            overflow: auto;
            font-size: 14px;
            line-height: 22px;
            padding: 20px 0;
            color: #999;
        }
        .towebmp4{
            cursor: pointer;
            padding: 4px 10px;
            background-color: #ff5519;
            color: #fff;
            font-size: 16px;
        }
        .playmp4{
            cursor: pointer;
            padding: 4px 10px;
            background-color: #228113;
            color: #fff;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div class="content">
        <form method="post" action="/search">
            <div class="video_search">
                <input type="text" name="weburl" class="video_search_text" placeholder="请输入网址,这里是抓取的https://www.juji.tv/dianshiju/linghunweixiugong/"><button type="submit" class="video_search_btn">搜索</button>
            </div>
        </form>
        <div class="video_info">
            <div class="video_logo"><img src="{{result['imgurl']}}" class="video_img"> </div>
            <div class="video_txt">
                <div class="video_title">{{result['title']}}</div>
                <div class="video_user">{{result['users']}}</div>
                <div class="video_detail">{{result['detail']}}</div>
            </div>
        </div>
        <div class="video_online">在线观看</div>
        <div class="video_ep">
            <ul>
            {% for item in result['episodes']%}
                <li>
                    <div class="video_ep_li">
                        <div class="video_play">
                            <a href="javascript:;" class="js-play" data-name="{{result['title']}}_{{item['name']}}" data-url="{{item['url']}}" title="播放"><img src="/static/img/play.png"><span class="video_play_name">{{item['name']}}</span></a>
                        </div>
                        <div class="video_down"><a href="javascript:;" class="js-down" data-name="{{result['title']}}_{{item['name']}}" data-url="{{item['url']}}" title="下载"><img src="/static/img/down.png"> </a> </div>
                    </div>
                </li>
            {% endfor%}
            </ul>
        </div>
        <div class="video_show">
            <!--播放视频-->
            <div class="video_con" style="display: none">
                <video id="player" class="video-js vjs-16-9 vjs-big-play-centered" controls preload="auto"  data-setup="{}"></video></div>
            <!--播放视频-->
            <!--查看下载进度-->
            <div class="video_log">
            </div>
            <!--查看下载进度-->
        </div>
        </div>

</body>
</html>

这里html页面的我就不在这里详细说了,这里是讲python,前端的知识点有兴趣后面可以讲讲,但是里面大家可以发现一些参数,比如:

{{result['title']}}                                    #意思是显示标题

{% for item in result['episodes']%}       #意思就是循环展示剧集

……

{% endfor %}

这些就是通过上面的形式来获取传递给页面的result参数,简单的说下,{{…}}这个是在页面中读取变量,{%%}这个是执行逻辑方法,跟asp,php,java的类似,在页面中代码混排,其实个人是不推荐这种方法,目前大趋势都流行前后端分离,完全可以用JS来调用方法,不需要胶水的一样的代码写法,这种不利用代码维护,如果不是全栈人员的话,修改起来很麻烦,这里只是为了简单快捷,所以直接用这种方式展示,来,我们运行run.py文件来看看结果:

至此我们就将爬取的视频信息通过网页的形式展示出来,这篇只是讲解如何实现页面展示,为了不干扰理解的过程,所以我将JS部分删除了。

认真的时光还是过得这么快,该到吃饭的时间的了,今天就到这里,江湖不说再见,咱们下篇见!

关注公众号,超越平凡才能成就自己

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章